Commit 256868a43c9dfabca8282ec75ee15b33e9df2c01

Authored by phong
1 parent b50303b97d

update page 1 to page 5 file lifelog.ppt

Showing 8 changed files with 106 additions and 4 deletions Inline Diff

LifeLog/LifeLog/AppDelegate.m
1 // 1 //
2 // AppDelegate.m 2 // AppDelegate.m
3 // LifeLog 3 // LifeLog
4 // 4 //
5 // Created by Nguyen Van Phong on 7/25/17. 5 // Created by Nguyen Van Phong on 7/25/17.
6 // Copyright © 2017 PhongNV. All rights reserved. 6 // Copyright © 2017 PhongNV. All rights reserved.
7 // 7 //
8 8
9 #import "AppDelegate.h" 9 #import "AppDelegate.h"
10 #import "LoginViewController.h" 10 #import "LoginViewController.h"
11 #import "HomeViewController.h" 11 #import "HomeViewController.h"
12 #import "HistoryViewController.h" 12 #import "HistoryViewController.h"
13 #import "RankingViewController.h" 13 #import "RankingViewController.h"
14 #import "MapViewController.h" 14 #import "MapViewController.h"
15 #import "SNSViewController.h" 15 #import "SNSViewController.h"
16 #import "ServerAPI.h"
16 17
17 @interface AppDelegate () 18 @interface AppDelegate ()
18 19
19 @end 20 @end
20 21
21 @implementation AppDelegate 22 @implementation AppDelegate
22 23
23 + (AppDelegate *)sharedAppDelegate { 24 + (AppDelegate *)sharedAppDelegate {
24 return (AppDelegate *)[UIApplication sharedApplication].delegate; 25 return (AppDelegate *)[UIApplication sharedApplication].delegate;
25 } 26 }
26 27
27 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { 28 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
28 // Override point for customization after application launch. 29 // Override point for customization after application launch.
29 self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds]; 30 self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
30 31
31 if ([[NSUserDefaults standardUserDefaults] objectForKey:@"User_Login"]) { 32 NSData *data = [[NSUserDefaults standardUserDefaults] objectForKey:kUser];
32 [self gotoMainMenu]; 33 User *user = (User *)[NSKeyedUnarchiver unarchiveObjectWithData:data];
33 } 34 if (user == nil) {
34 else {
35 LoginViewController *loginVC = [[LoginViewController alloc] initWithNibName:@"LoginViewController" bundle:nil]; 35 LoginViewController *loginVC = [[LoginViewController alloc] initWithNibName:@"LoginViewController" bundle:nil];
36 UINavigationController *navigation = [[UINavigationController alloc] initWithRootViewController:loginVC]; 36 UINavigationController *navigation = [[UINavigationController alloc] initWithRootViewController:loginVC];
37 self.window.rootViewController = navigation; 37 self.window.rootViewController = navigation;
38 [self.window makeKeyAndVisible]; 38 [self.window makeKeyAndVisible];
39 }
40 else {
41 [self gotoMainMenu];
39 } 42 }
40 43
41 return YES; 44 return YES;
42 } 45 }
43 46
44 47
45 - (void)applicationWillResignActive:(UIApplication *)application { 48 - (void)applicationWillResignActive:(UIApplication *)application {
46 // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. 49 // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
47 // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. 50 // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
48 } 51 }
49 52
50 53
51 - (void)applicationDidEnterBackground:(UIApplication *)application { 54 - (void)applicationDidEnterBackground:(UIApplication *)application {
52 // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 55 // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
53 // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. 56 // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
54 } 57 }
55 58
56 59
57 - (void)applicationWillEnterForeground:(UIApplication *)application { 60 - (void)applicationWillEnterForeground:(UIApplication *)application {
58 // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. 61 // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
59 } 62 }
60 63
61 64
62 - (void)applicationDidBecomeActive:(UIApplication *)application { 65 - (void)applicationDidBecomeActive:(UIApplication *)application {
63 // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. 66 // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
64 } 67 }
65 68
66 69
67 - (void)applicationWillTerminate:(UIApplication *)application { 70 - (void)applicationWillTerminate:(UIApplication *)application {
68 // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. 71 // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
69 } 72 }
70 73
71 - (void)gotoMainMenu 74 - (void)gotoMainMenu
72 { 75 {
73 UITabBarController *tabBarViewController = [[UITabBarController alloc] init]; 76 UITabBarController *tabBarViewController = [[UITabBarController alloc] init];
74 77
75 HomeViewController *homeVC = [[HomeViewController alloc] initWithNibName:@"HomeViewController" bundle:nil]; 78 HomeViewController *homeVC = [[HomeViewController alloc] initWithNibName:@"HomeViewController" bundle:nil];
76 UINavigationController *naviToday = [[UINavigationController alloc] initWithRootViewController:homeVC]; 79 UINavigationController *naviToday = [[UINavigationController alloc] initWithRootViewController:homeVC];
77 naviToday.tabBarItem = [[UITabBarItem alloc] initWithTitle:NSLocalizedString(@"lifelog.tapbar.today", @"") image:[UIImage imageNamed:@"tapbar_today"] tag:1]; 80 naviToday.tabBarItem = [[UITabBarItem alloc] initWithTitle:NSLocalizedString(@"lifelog.tapbar.today", @"") image:[UIImage imageNamed:@"tapbar_today"] tag:1];
78 naviToday.navigationBar.hidden = YES; 81 naviToday.navigationBar.hidden = YES;
79 82
80 HistoryViewController *historyVC = [[HistoryViewController alloc] initWithNibName:@"HistoryViewController" bundle:nil]; 83 HistoryViewController *historyVC = [[HistoryViewController alloc] initWithNibName:@"HistoryViewController" bundle:nil];
81 UINavigationController *naviHistory = [[UINavigationController alloc] initWithRootViewController:historyVC]; 84 UINavigationController *naviHistory = [[UINavigationController alloc] initWithRootViewController:historyVC];
82 naviHistory.tabBarItem = [[UITabBarItem alloc] initWithTitle:NSLocalizedString(@"lifelog.tapbar.history", @"") image:[UIImage imageNamed:@"tapbar_history"] tag:2]; 85 naviHistory.tabBarItem = [[UITabBarItem alloc] initWithTitle:NSLocalizedString(@"lifelog.tapbar.history", @"") image:[UIImage imageNamed:@"tapbar_history"] tag:2];
83 86
84 RankingViewController *rankingVC = [[RankingViewController alloc] initWithNibName:@"RankingViewController" bundle:nil]; 87 RankingViewController *rankingVC = [[RankingViewController alloc] initWithNibName:@"RankingViewController" bundle:nil];
85 UINavigationController *naviRanking = [[UINavigationController alloc] initWithRootViewController:rankingVC]; 88 UINavigationController *naviRanking = [[UINavigationController alloc] initWithRootViewController:rankingVC];
86 naviRanking.tabBarItem = [[UITabBarItem alloc] initWithTitle:NSLocalizedString(@"lifelog.tapbar.ranking", @"") image:[UIImage imageNamed:@"tapbar_ranking"] tag:3]; 89 naviRanking.tabBarItem = [[UITabBarItem alloc] initWithTitle:NSLocalizedString(@"lifelog.tapbar.ranking", @"") image:[UIImage imageNamed:@"tapbar_ranking"] tag:3];
87 90
88 MapViewController *mapVC = [[MapViewController alloc] initWithNibName:@"MapViewController" bundle:nil]; 91 MapViewController *mapVC = [[MapViewController alloc] initWithNibName:@"MapViewController" bundle:nil];
89 UINavigationController *naviMap = [[UINavigationController alloc] initWithRootViewController:mapVC]; 92 UINavigationController *naviMap = [[UINavigationController alloc] initWithRootViewController:mapVC];
90 naviMap.tabBarItem = [[UITabBarItem alloc] initWithTitle:NSLocalizedString(@"lifelog.tapbar.map", @"") image:[UIImage imageNamed:@"tapbar_map"] tag:4]; 93 naviMap.tabBarItem = [[UITabBarItem alloc] initWithTitle:NSLocalizedString(@"lifelog.tapbar.map", @"") image:[UIImage imageNamed:@"tapbar_map"] tag:4];
91 94
92 SNSViewController *snsVC = [[SNSViewController alloc] initWithNibName:@"SNSViewController" bundle:nil]; 95 SNSViewController *snsVC = [[SNSViewController alloc] initWithNibName:@"SNSViewController" bundle:nil];
93 UINavigationController *naviSNS = [[UINavigationController alloc] initWithRootViewController:snsVC]; 96 UINavigationController *naviSNS = [[UINavigationController alloc] initWithRootViewController:snsVC];
94 naviSNS.tabBarItem = [[UITabBarItem alloc] initWithTitle:NSLocalizedString(@"lifelog.tapbar.sns", @"") image:[UIImage imageNamed:@"tapbar_sns"] tag:5]; 97 naviSNS.tabBarItem = [[UITabBarItem alloc] initWithTitle:NSLocalizedString(@"lifelog.tapbar.sns", @"") image:[UIImage imageNamed:@"tapbar_sns"] tag:5];
95 98
96 tabBarViewController.viewControllers = [NSArray arrayWithObjects:naviToday, naviHistory, naviRanking, naviMap, naviSNS, nil]; 99 tabBarViewController.viewControllers = [NSArray arrayWithObjects:naviToday, naviHistory, naviRanking, naviMap, naviSNS, nil];
97 100
98 self.window.rootViewController = tabBarViewController; 101 self.window.rootViewController = tabBarViewController;
99 [self.window makeKeyAndVisible]; 102 [self.window makeKeyAndVisible];
100 } 103 }
101 104
102 @end 105 @end
LifeLog/LifeLog/HomeViewController.m
1 // 1 //
2 // HomeViewController.m 2 // HomeViewController.m
3 // LifeLog 3 // LifeLog
4 // 4 //
5 // Created by Nguyen Van Phong on 7/25/17. 5 // Created by Nguyen Van Phong on 7/25/17.
6 // Copyright © 2017 PhongNV. All rights reserved. 6 // Copyright © 2017 PhongNV. All rights reserved.
7 // 7 //
8 8
9 #import "HomeViewController.h" 9 #import "HomeViewController.h"
10 #import "NSDate+helper.h" 10 #import "NSDate+helper.h"
11 #import <CoreMotion/CoreMotion.h> 11 #import <CoreMotion/CoreMotion.h>
12 #import "CMMotionActivityExtra.h" 12 #import "CMMotionActivityExtra.h"
13 #import "TodayViewController.h" 13 #import "TodayViewController.h"
14 #import "Utilities.h" 14 #import "Utilities.h"
15 #import <MBProgressHUD/MBProgressHUD.h> 15 #import <MBProgressHUD/MBProgressHUD.h>
16 #import "ServerAPI.h"
16 17
17 static NSInteger numberTotal = 10000; 18 static NSInteger numberTotal = 10000;
18 19
19 @interface HomeViewController () 20 @interface HomeViewController ()
20 { 21 {
21 MBProgressHUD *progressHud; 22 MBProgressHUD *progressHud;
22 } 23 }
23 @property (nonatomic, weak) IBOutlet UILabel *lblTitle; 24 @property (nonatomic, weak) IBOutlet UILabel *lblTitle;
24 @property (nonatomic, weak) IBOutlet UIImageView *avatar; 25 @property (nonatomic, weak) IBOutlet UIImageView *avatar;
25 @property (nonatomic, weak) IBOutlet UILabel *lblDateCurrent; 26 @property (nonatomic, weak) IBOutlet UILabel *lblDateCurrent;
26 @property (nonatomic, weak) IBOutlet UILabel *lblValueStep; 27 @property (nonatomic, weak) IBOutlet UILabel *lblValueStep;
27 @property (nonatomic, weak) IBOutlet UILabel *lblUnitStep; 28 @property (nonatomic, weak) IBOutlet UILabel *lblUnitStep;
28 @property (nonatomic, weak) IBOutlet UILabel *lblValueStepOther; 29 @property (nonatomic, weak) IBOutlet UILabel *lblValueStepOther;
29 @property (nonatomic, weak) IBOutlet UILabel *lblPercent; 30 @property (nonatomic, weak) IBOutlet UILabel *lblPercent;
30 @property (nonatomic, weak) IBOutlet UILabel *lblNotice; 31 @property (nonatomic, weak) IBOutlet UILabel *lblNotice;
31 @property (weak, nonatomic) IBOutlet UISegmentedControl *segmentHome; 32 @property (weak, nonatomic) IBOutlet UISegmentedControl *segmentHome;
32 33
33 @property (nonatomic, strong) CMPedometer *pedometer; 34 @property (nonatomic, strong) CMPedometer *pedometer;
34 @property (nonatomic, strong) CMMotionActivityManager *motionActivityManager; 35 @property (nonatomic, strong) CMMotionActivityManager *motionActivityManager;
35 @property (nonatomic, strong) NSOperationQueue *operationQueue; 36 @property (nonatomic, strong) NSOperationQueue *operationQueue;
36 @property (nonatomic, strong) NSTimer *timer; 37 @property (nonatomic, strong) NSTimer *timer;
37 @property (nonatomic, assign) NSInteger bike; 38 @property (nonatomic, assign) NSInteger bike;
38 @property (nonatomic, assign) NSInteger walking; 39 @property (nonatomic, assign) NSInteger walking;
39 @property (nonatomic, assign) NSInteger running; 40 @property (nonatomic, assign) NSInteger running;
40 @property (nonatomic, strong) NSDate *dateCurrent; 41 @property (nonatomic, strong) NSDate *dateCurrent;
41 42
42 //@property (nonatomic, assign) BOOL isRequesting; 43 //@property (nonatomic, assign) BOOL isRequesting;
43 @property (nonatomic, assign) int totalRequest; 44 @property (nonatomic, assign) int totalRequest;
44 @property (nonatomic, assign) int countComplete; 45 @property (nonatomic, assign) int countComplete;
45 46
46 @end 47 @end
47 48
48 @implementation HomeViewController 49 @implementation HomeViewController
49 50
50 - (void)viewDidLoad { 51 - (void)viewDidLoad {
51 [super viewDidLoad]; 52 [super viewDidLoad];
52 // Do any additional setup after loading the view from its nib. 53 // Do any additional setup after loading the view from its nib.
53 self.lblTitle.text = NSLocalizedString(@"lifelog.home.title", nil); 54 self.lblTitle.text = NSLocalizedString(@"lifelog.home.title", nil);
54 55
55 [self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.topLayoutGuide attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:self.lblTitle attribute:NSLayoutAttributeTop multiplier:1 constant:0]]; 56 [self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.topLayoutGuide attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:self.lblTitle attribute:NSLayoutAttributeTop multiplier:1 constant:0]];
56 57
57 self.avatar.backgroundColor = [UIColor whiteColor]; 58 self.avatar.backgroundColor = [UIColor whiteColor];
58 self.avatar.layer.borderWidth = 2.0f; 59 self.avatar.layer.borderWidth = 2.0f;
59 self.avatar.layer.borderColor = [[UIColor whiteColor] CGColor]; 60 self.avatar.layer.borderColor = [[UIColor whiteColor] CGColor];
60 self.avatar.layer.cornerRadius = self.avatar.frame.size.width/2.0f; 61 self.avatar.layer.cornerRadius = self.avatar.frame.size.width/2.0f;
61 self.avatar.layer.masksToBounds = YES; 62 self.avatar.layer.masksToBounds = YES;
63 NSData *data = [[NSUserDefaults standardUserDefaults] objectForKey:kUser];
64 User *user = (User *)[NSKeyedUnarchiver unarchiveObjectWithData:data];
65 if (user != nil) {
66 NSString *linkImage = [NSString stringWithFormat:@"%@%@", kServerAddress, user.profile_image];
67 NSURL *urlImage = [NSURL URLWithString:linkImage];
68 NSURLSessionConfiguration *sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration];
69 sessionConfig.timeoutIntervalForRequest = 30.0;
70 sessionConfig.timeoutIntervalForResource = 60.0;
71 sessionConfig.HTTPMaximumConnectionsPerHost = 20;
72 sessionConfig.allowsCellularAccess = YES;
73 HomeViewController __weak *weakSelf = self;
74 NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfig];
75 NSURLSessionDataTask *downloadPhotoTask = [session
76 dataTaskWithURL:urlImage completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
77 if (weakSelf == nil)
78 {
79 return;
80 }
81 if (error == nil) {
82 UIImage *image = [[UIImage alloc] initWithData:data];
83 [[NSOperationQueue mainQueue] addOperationWithBlock:^{
84 weakSelf.avatar.image = image;
85 }];
86 }
87 }];
88 [downloadPhotoTask resume];
89 }
90
62 self.lblNotice.text = NSLocalizedString(@"lifelog.home.notice", nil); 91 self.lblNotice.text = NSLocalizedString(@"lifelog.home.notice", nil);
63 92
64 _dateCurrent = [NSDate date]; 93 _dateCurrent = [NSDate date];
65 self.lblDateCurrent.text = [NSString stringWithFormat:@"%ld%@%ld%@%ld%@", (long)[_dateCurrent getYear], NSLocalizedString(@"lifelog.common.year", nil), (long)[_dateCurrent getMonth], NSLocalizedString(@"lifelog.common.month", nil), (long)[_dateCurrent getDay], NSLocalizedString(@"lifelog.common.day", nil)]; 94 self.lblDateCurrent.text = [NSString stringWithFormat:@"%ld%@%ld%@%ld%@", (long)[_dateCurrent getYear], NSLocalizedString(@"lifelog.common.year", nil), (long)[_dateCurrent getMonth], NSLocalizedString(@"lifelog.common.month", nil), (long)[_dateCurrent getDay], NSLocalizedString(@"lifelog.common.day", nil)];
66 95
67 self.lblUnitStep.text = NSLocalizedString(@"lifelog.home.unit.step", nil); 96 self.lblUnitStep.text = NSLocalizedString(@"lifelog.home.unit.step", nil);
68 97
69 if ([CMPedometer isStepCountingAvailable]) { 98 if ([CMPedometer isStepCountingAvailable]) {
70 _pedometer = [[CMPedometer alloc] init]; 99 _pedometer = [[CMPedometer alloc] init];
71 } 100 }
72 if ([CMMotionActivityManager isActivityAvailable]) { 101 if ([CMMotionActivityManager isActivityAvailable]) {
73 _motionActivityManager = [[CMMotionActivityManager alloc] init]; 102 _motionActivityManager = [[CMMotionActivityManager alloc] init];
74 } 103 }
75 _operationQueue = [[NSOperationQueue alloc] init]; 104 _operationQueue = [[NSOperationQueue alloc] init];
76 _bike = 0; 105 _bike = 0;
77 _walking = 0; 106 _walking = 0;
78 _running = 0; 107 _running = 0;
79 _segmentHome.selectedSegmentIndex = 1; 108 _segmentHome.selectedSegmentIndex = 1;
80 // _isRequesting = NO; 109 // _isRequesting = NO;
81 _totalRequest = 0; 110 _totalRequest = 0;
82 _countComplete = 0; 111 _countComplete = 0;
83 112
84 progressHud = [MBProgressHUD showHUDAddedTo:self.view animated:YES]; 113 progressHud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
85 progressHud.mode = MBProgressHUDModeIndeterminate; 114 progressHud.mode = MBProgressHUDModeIndeterminate;
86 progressHud.detailsLabel.text = NSLocalizedString(@"lifelog.home.progressHud.title", nil); 115 progressHud.detailsLabel.text = NSLocalizedString(@"lifelog.home.progressHud.title", nil);
87 } 116 }
88 117
89 - (void)viewWillAppear:(BOOL)animated { 118 - (void)viewWillAppear:(BOOL)animated {
90 [super viewWillAppear:animated]; 119 [super viewWillAppear:animated];
91 // _timer = [NSTimer scheduledTimerWithTimeInterval:1.5f target:self selector:@selector(countStep) userInfo:nil repeats:YES]; 120 // _timer = [NSTimer scheduledTimerWithTimeInterval:1.5f target:self selector:@selector(countStep) userInfo:nil repeats:YES];
92 // [_timer fire]; 121 // [_timer fire];
93 [self countStep]; 122 [self countStep];
94 } 123 }
95 124
96 - (void)viewWillDisappear:(BOOL)animated { 125 - (void)viewWillDisappear:(BOOL)animated {
97 [super viewWillDisappear:animated]; 126 [super viewWillDisappear:animated];
98 //[_timer invalidate]; 127 //[_timer invalidate];
99 } 128 }
100 129
101 - (void)didReceiveMemoryWarning { 130 - (void)didReceiveMemoryWarning {
102 [super didReceiveMemoryWarning]; 131 [super didReceiveMemoryWarning];
103 // Dispose of any resources that can be recreated. 132 // Dispose of any resources that can be recreated.
104 } 133 }
105 134
106 #pragma mark - IBAction 135 #pragma mark - IBAction
107 - (IBAction)menuButtonTouchUpInside:(id)sender 136 - (IBAction)menuButtonTouchUpInside:(id)sender
108 { 137 {
109 138
110 } 139 }
111 140
112 - (IBAction)todayButtonTouchUpInside:(id)sender 141 - (IBAction)todayButtonTouchUpInside:(id)sender
113 { 142 {
114 TodayViewController *todayVC = [[TodayViewController alloc] initWithNibName:@"TodayViewController" bundle:nil]; 143 TodayViewController *todayVC = [[TodayViewController alloc] initWithNibName:@"TodayViewController" bundle:nil];
115 [self.navigationController pushViewController:todayVC animated:YES]; 144 [self.navigationController pushViewController:todayVC animated:YES];
116 } 145 }
117 146
118 - (IBAction)leftButtonTouchUpInside:(id)sender 147 - (IBAction)leftButtonTouchUpInside:(id)sender
119 { 148 {
120 self.dateCurrent = [self.dateCurrent dateByAddingTimeInterval:-(24*60*60)]; 149 self.dateCurrent = [self.dateCurrent dateByAddingTimeInterval:-(24*60*60)];
121 self.lblDateCurrent.text = [NSString stringWithFormat:@"%ld%@%ld%@%ld%@", (long)[_dateCurrent getYear], NSLocalizedString(@"lifelog.common.year", nil), (long)[_dateCurrent getMonth], NSLocalizedString(@"lifelog.common.month", nil), (long)[_dateCurrent getDay], NSLocalizedString(@"lifelog.common.day", nil)]; 150 self.lblDateCurrent.text = [NSString stringWithFormat:@"%ld%@%ld%@%ld%@", (long)[_dateCurrent getYear], NSLocalizedString(@"lifelog.common.year", nil), (long)[_dateCurrent getMonth], NSLocalizedString(@"lifelog.common.month", nil), (long)[_dateCurrent getDay], NSLocalizedString(@"lifelog.common.day", nil)];
122 [self countStep]; 151 [self countStep];
123 } 152 }
124 153
125 - (IBAction)rightButtonTouchUpInside:(id)sender 154 - (IBAction)rightButtonTouchUpInside:(id)sender
126 { 155 {
127 self.dateCurrent = [self.dateCurrent dateByAddingTimeInterval:24*60*60]; 156 self.dateCurrent = [self.dateCurrent dateByAddingTimeInterval:24*60*60];
128 self.lblDateCurrent.text = [NSString stringWithFormat:@"%ld%@%ld%@%ld%@", (long)[_dateCurrent getYear], NSLocalizedString(@"lifelog.common.year", nil), (long)[_dateCurrent getMonth], NSLocalizedString(@"lifelog.common.month", nil), (long)[_dateCurrent getDay], NSLocalizedString(@"lifelog.common.day", nil)]; 157 self.lblDateCurrent.text = [NSString stringWithFormat:@"%ld%@%ld%@%ld%@", (long)[_dateCurrent getYear], NSLocalizedString(@"lifelog.common.year", nil), (long)[_dateCurrent getMonth], NSLocalizedString(@"lifelog.common.month", nil), (long)[_dateCurrent getDay], NSLocalizedString(@"lifelog.common.day", nil)];
129 [self countStep]; 158 [self countStep];
130 } 159 }
131 160
132 - (IBAction)segmentValueChange:(id)sender { 161 - (IBAction)segmentValueChange:(id)sender {
133 [self updateStepUI]; 162 [self updateStepUI];
134 } 163 }
135 164
136 #pragma mark - Functions Private 165 #pragma mark - Functions Private
137 - (void)countStep 166 - (void)countStep
138 { 167 {
139 // if (self.isRequesting == YES) { 168 // if (self.isRequesting == YES) {
140 // return; 169 // return;
141 // } 170 // }
142 if ([CMMotionActivityManager isActivityAvailable]) { 171 if ([CMMotionActivityManager isActivityAvailable]) {
143 [progressHud showAnimated:YES]; 172 [progressHud showAnimated:YES];
144 [progressHud setHidden:NO]; 173 [progressHud setHidden:NO];
145 // self.isRequesting = YES; 174 // self.isRequesting = YES;
146 self.bike = 0; 175 self.bike = 0;
147 self.walking = 0; 176 self.walking = 0;
148 self.running = 0; 177 self.running = 0;
149 NSDate *startDate = [self.dateCurrent beginningAtMidnightOfDay]; 178 NSDate *startDate = [self.dateCurrent beginningAtMidnightOfDay];
150 NSDate *endDate = [startDate dateByAddingTimeInterval:(24*60*60 - 1)]; 179 NSDate *endDate = [startDate dateByAddingTimeInterval:(24*60*60 - 1)];
151 180
152 HomeViewController __weak *weakSelf = self; 181 HomeViewController __weak *weakSelf = self;
153 dispatch_queue_t myQueue = dispatch_queue_create("mobileworld.jp.lifelog", NULL); 182 dispatch_queue_t myQueue = dispatch_queue_create("mobileworld.jp.lifelog", NULL);
154 dispatch_async(myQueue, ^{ 183 dispatch_async(myQueue, ^{
155 if (weakSelf == nil) { 184 if (weakSelf == nil) {
156 return ; 185 return ;
157 } 186 }
158 187
159 [weakSelf.motionActivityManager queryActivityStartingFromDate:startDate toDate:endDate toQueue:_operationQueue withHandler:^(NSArray<CMMotionActivity *> * _Nullable activities, NSError * _Nullable error) { 188 [weakSelf.motionActivityManager queryActivityStartingFromDate:startDate toDate:endDate toQueue:_operationQueue withHandler:^(NSArray<CMMotionActivity *> * _Nullable activities, NSError * _Nullable error) {
160 if (error || activities.count <= 0) { 189 if (error || activities.count <= 0) {
161 weakSelf.totalRequest = 0; 190 weakSelf.totalRequest = 0;
162 weakSelf.countComplete = 0; 191 weakSelf.countComplete = 0;
163 dispatch_async(dispatch_get_main_queue(), ^{ 192 dispatch_async(dispatch_get_main_queue(), ^{
164 [weakSelf updateStepUI]; 193 [weakSelf updateStepUI];
165 }); 194 });
166 return ; 195 return ;
167 } 196 }
168 // set EndDate 197 // set EndDate
169 weakSelf.totalRequest = (int)activities.count; 198 weakSelf.totalRequest = (int)activities.count;
170 NSMutableArray *arrayActivities = [[NSMutableArray alloc] init]; 199 NSMutableArray *arrayActivities = [[NSMutableArray alloc] init];
171 for (int i = 0; i < activities.count; i++) { 200 for (int i = 0; i < activities.count; i++) {
172 CMMotionActivity *activity = [activities objectAtIndex:i]; 201 CMMotionActivity *activity = [activities objectAtIndex:i];
173 CMMotionActivityExtra *activityExtra = [[CMMotionActivityExtra alloc] init]; 202 CMMotionActivityExtra *activityExtra = [[CMMotionActivityExtra alloc] init];
174 activityExtra.activity = activity; 203 activityExtra.activity = activity;
175 if (i == activities.count - 1) { 204 if (i == activities.count - 1) {
176 activityExtra.endDate = endDate; 205 activityExtra.endDate = endDate;
177 } 206 }
178 else { 207 else {
179 CMMotionActivity *activityNext = [activities objectAtIndex:i+1]; 208 CMMotionActivity *activityNext = [activities objectAtIndex:i+1];
180 activityExtra.endDate = activityNext.startDate; 209 activityExtra.endDate = activityNext.startDate;
181 } 210 }
182 [arrayActivities addObject:activityExtra]; 211 [arrayActivities addObject:activityExtra];
183 } 212 }
184 213
185 for (CMMotionActivityExtra *activityExtra in arrayActivities) { 214 for (CMMotionActivityExtra *activityExtra in arrayActivities) {
186 // NSLog(@"%@", activityExtra.activity.startDate); 215 // NSLog(@"%@", activityExtra.activity.startDate);
187 [weakSelf.pedometer queryPedometerDataFromDate:activityExtra.activity.startDate toDate:activityExtra.endDate withHandler:^(CMPedometerData * _Nullable pedometerData, NSError * _Nullable error) { 216 [weakSelf.pedometer queryPedometerDataFromDate:activityExtra.activity.startDate toDate:activityExtra.endDate withHandler:^(CMPedometerData * _Nullable pedometerData, NSError * _Nullable error) {
188 NSInteger numberStep = [pedometerData.numberOfSteps integerValue]; 217 NSInteger numberStep = [pedometerData.numberOfSteps integerValue];
189 218
190 if (activityExtra.activity.cycling) { 219 if (activityExtra.activity.cycling) {
191 // self.bike 220 // self.bike
192 weakSelf.bike += numberStep; 221 weakSelf.bike += numberStep;
193 //NSLog(@"Step cycling"); 222 //NSLog(@"Step cycling");
194 } 223 }
195 else if (activityExtra.activity.walking) { 224 else if (activityExtra.activity.walking) {
196 // self.walking 225 // self.walking
197 weakSelf.walking += numberStep; 226 weakSelf.walking += numberStep;
198 //NSLog(@"Step walking"); 227 //NSLog(@"Step walking");
199 } 228 }
200 else if (activityExtra.activity.running) { 229 else if (activityExtra.activity.running) {
201 weakSelf.running += numberStep; 230 weakSelf.running += numberStep;
202 //NSLog(@"Step running"); 231 //NSLog(@"Step running");
203 } 232 }
204 else { 233 else {
205 // unknown 234 // unknown
206 //NSLog(@"Step unknown"); 235 //NSLog(@"Step unknown");
207 } 236 }
208 // NSLog(@"Number of step--> %ld", numberStep); 237 // NSLog(@"Number of step--> %ld", numberStep);
209 weakSelf.countComplete += 1; 238 weakSelf.countComplete += 1;
210 dispatch_async(dispatch_get_main_queue(), ^{ 239 dispatch_async(dispatch_get_main_queue(), ^{
211 [weakSelf updateStepUI]; 240 [weakSelf updateStepUI];
212 }); 241 });
213 }]; 242 }];
214 } 243 }
215 // NSLog(@"-----------------------------------------------------"); 244 // NSLog(@"-----------------------------------------------------");
216 }]; 245 }];
217 }); 246 });
218 } 247 }
219 else { 248 else {
220 [progressHud setHidden:YES]; 249 [progressHud setHidden:YES];
221 } 250 }
222 } 251 }
223 252
224 - (void)updateStepUI //:(NSInteger)numberStep 253 - (void)updateStepUI //:(NSInteger)numberStep
225 { 254 {
226 if (self.totalRequest == self.countComplete) { 255 if (self.totalRequest == self.countComplete) {
227 switch (self.segmentHome.selectedSegmentIndex) { 256 switch (self.segmentHome.selectedSegmentIndex) {
228 case 0: 257 case 0:
229 self.lblValueStep.text = [Utilities addCommaFromNumber:self.bike]; 258 self.lblValueStep.text = [Utilities addCommaFromNumber:self.bike];
230 self.lblValueStepOther.text = [NSString stringWithFormat:@"%@ %ld", NSLocalizedString(@"lifelog.today.remaining.other", nil), numberTotal - self.bike]; 259 self.lblValueStepOther.text = [NSString stringWithFormat:@"%@ %ld", NSLocalizedString(@"lifelog.today.remaining.other", nil), numberTotal - self.bike];
231 self.lblPercent.text = [NSString stringWithFormat:@"%@ %i%@", NSLocalizedString(@"lifelog.today.text.percent", nil), (int)(self.bike*100/numberTotal), NSLocalizedString(@"lifelog.today.percent", nil)]; 260 self.lblPercent.text = [NSString stringWithFormat:@"%@ %i%@", NSLocalizedString(@"lifelog.today.text.percent", nil), (int)(self.bike*100/numberTotal), NSLocalizedString(@"lifelog.today.percent", nil)];
232 break; 261 break;
233 262
234 case 1: 263 case 1:
235 self.lblValueStep.text = [Utilities addCommaFromNumber:self.walking]; 264 self.lblValueStep.text = [Utilities addCommaFromNumber:self.walking];
236 self.lblValueStepOther.text = [NSString stringWithFormat:@"%@ %ld", NSLocalizedString(@"lifelog.today.remaining.other", nil), numberTotal - self.walking]; 265 self.lblValueStepOther.text = [NSString stringWithFormat:@"%@ %ld", NSLocalizedString(@"lifelog.today.remaining.other", nil), numberTotal - self.walking];
237 self.lblPercent.text = [NSString stringWithFormat:@"%@ %i%@", NSLocalizedString(@"lifelog.today.text.percent", nil), (int)(self.walking*100/numberTotal), NSLocalizedString(@"lifelog.today.percent", nil)]; 266 self.lblPercent.text = [NSString stringWithFormat:@"%@ %i%@", NSLocalizedString(@"lifelog.today.text.percent", nil), (int)(self.walking*100/numberTotal), NSLocalizedString(@"lifelog.today.percent", nil)];
238 break; 267 break;
239 268
240 case 2: 269 case 2:
241 self.lblValueStep.text = [Utilities addCommaFromNumber:self.running]; 270 self.lblValueStep.text = [Utilities addCommaFromNumber:self.running];
242 self.lblValueStepOther.text = [NSString stringWithFormat:@"%@ %ld", NSLocalizedString(@"lifelog.today.remaining.other", nil), numberTotal - self.running]; 271 self.lblValueStepOther.text = [NSString stringWithFormat:@"%@ %ld", NSLocalizedString(@"lifelog.today.remaining.other", nil), numberTotal - self.running];
243 self.lblPercent.text = [NSString stringWithFormat:@"%@ %i%@", NSLocalizedString(@"lifelog.today.text.percent", nil), (int)(self.running*100/numberTotal), NSLocalizedString(@"lifelog.today.percent", nil)]; 272 self.lblPercent.text = [NSString stringWithFormat:@"%@ %i%@", NSLocalizedString(@"lifelog.today.text.percent", nil), (int)(self.running*100/numberTotal), NSLocalizedString(@"lifelog.today.percent", nil)];
244 break; 273 break;
245 274
246 default: 275 default:
247 break; 276 break;
248 } 277 }
249 // NSLog(@"Walking: %ld || Running: %ld || Bike: %ld", self.walking, self.running, self.bike); 278 // NSLog(@"Walking: %ld || Running: %ld || Bike: %ld", self.walking, self.running, self.bike);
250 // self.isRequesting = NO; 279 // self.isRequesting = NO;
251 self.countComplete = 0; 280 self.countComplete = 0;
252 self.totalRequest = 0; 281 self.totalRequest = 0;
253 [progressHud setHidden:YES]; 282 [progressHud setHidden:YES];
254 } 283 }
255 } 284 }
256 285
257 @end 286 @end
258 287
LifeLog/LifeLog/LoginViewController.m
1 // 1 //
2 // LoginViewController.m 2 // LoginViewController.m
3 // LifeLog 3 // LifeLog
4 // 4 //
5 // Created by Nguyen Van Phong on 7/30/17. 5 // Created by Nguyen Van Phong on 7/30/17.
6 // Copyright © 2017 PhongNV. All rights reserved. 6 // Copyright © 2017 PhongNV. All rights reserved.
7 // 7 //
8 8
9 #import "LoginViewController.h" 9 #import "LoginViewController.h"
10 #import "ServerAPI.h" 10 #import "ServerAPI.h"
11 #import "AppDelegate.h" 11 #import "AppDelegate.h"
12 #import "RegisterViewController.h" 12 #import "RegisterViewController.h"
13 #import "Utilities.h" 13 #import "Utilities.h"
14 #import "ConfirmForgetPassViewController.h" 14 #import "ConfirmForgetPassViewController.h"
15 15
16 @interface LoginViewController () 16 @interface LoginViewController ()
17 @property (nonatomic, weak) IBOutlet UILabel *lblEmail; 17 @property (nonatomic, weak) IBOutlet UILabel *lblEmail;
18 @property (nonatomic, weak) IBOutlet UILabel *lblPassword; 18 @property (nonatomic, weak) IBOutlet UILabel *lblPassword;
19 @property (nonatomic, weak) IBOutlet UILabel *lblRegister; 19 @property (nonatomic, weak) IBOutlet UILabel *lblRegister;
20 @property (nonatomic, weak) IBOutlet UITextField *tfEmail; 20 @property (nonatomic, weak) IBOutlet UITextField *tfEmail;
21 @property (nonatomic, weak) IBOutlet UITextField *tfPassword; 21 @property (nonatomic, weak) IBOutlet UITextField *tfPassword;
22 @property (nonatomic, weak) IBOutlet UIButton *btnLogin; 22 @property (nonatomic, weak) IBOutlet UIButton *btnLogin;
23 @property (nonatomic, weak) IBOutlet UIButton *btnRegist; 23 @property (nonatomic, weak) IBOutlet UIButton *btnRegist;
24 @property (nonatomic, weak) IBOutlet UIButton *btnForget; 24 @property (nonatomic, weak) IBOutlet UIButton *btnForget;
25 @end 25 @end
26 26
27 @implementation LoginViewController 27 @implementation LoginViewController
28 28
29 - (void)viewDidLoad { 29 - (void)viewDidLoad {
30 [super viewDidLoad]; 30 [super viewDidLoad];
31 // Do any additional setup after loading the view from its nib. 31 // Do any additional setup after loading the view from its nib.
32 self.title = NSLocalizedString(@"lifelog.login.title", nil); 32 self.title = NSLocalizedString(@"lifelog.login.title", nil);
33 33
34 self.lblEmail.text = NSLocalizedString(@"lifelog.common.email", nil); 34 self.lblEmail.text = NSLocalizedString(@"lifelog.common.email", nil);
35 self.lblPassword.text = NSLocalizedString(@"lifelog.common.password", nil); 35 self.lblPassword.text = NSLocalizedString(@"lifelog.common.password", nil);
36 self.lblRegister.text = NSLocalizedString(@"lifelog.login.label.register", nil); 36 self.lblRegister.text = NSLocalizedString(@"lifelog.login.label.register", nil);
37 37
38 [self.btnLogin setTitle:NSLocalizedString(@"lifelog.login.button.login", nil) forState:UIControlStateNormal]; 38 [self.btnLogin setTitle:NSLocalizedString(@"lifelog.login.button.login", nil) forState:UIControlStateNormal];
39 [self.btnRegist setTitle:NSLocalizedString(@"lifelog.login.button.register", nil) forState:UIControlStateNormal]; 39 [self.btnRegist setTitle:NSLocalizedString(@"lifelog.login.button.register", nil) forState:UIControlStateNormal];
40 40
41 NSMutableAttributedString *forgetString = [[NSMutableAttributedString alloc] initWithString:NSLocalizedString(@"lifelog.login.forget.password", nil)]; 41 NSMutableAttributedString *forgetString = [[NSMutableAttributedString alloc] initWithString:NSLocalizedString(@"lifelog.login.forget.password", nil)];
42 [forgetString addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleSingle] range:NSMakeRange(0, [forgetString length])]; 42 [forgetString addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleSingle] range:NSMakeRange(0, [forgetString length])];
43 // Or for adding Colored text use---------- 43 // Or for adding Colored text use----------
44 UIColor* textColor = [UIColor blueColor]; 44 UIColor* textColor = [UIColor blueColor];
45 [forgetString setAttributes:@{NSForegroundColorAttributeName:textColor,NSUnderlineStyleAttributeName:[NSNumber numberWithInteger:NSUnderlineStyleSingle]} range:NSMakeRange(0,[forgetString length])]; 45 [forgetString setAttributes:@{NSForegroundColorAttributeName:textColor,NSUnderlineStyleAttributeName:[NSNumber numberWithInteger:NSUnderlineStyleSingle]} range:NSMakeRange(0,[forgetString length])];
46 // Or for adding Colored text use---------- 46 // Or for adding Colored text use----------
47 [_btnForget setAttributedTitle:forgetString forState:UIControlStateNormal]; 47 [_btnForget setAttributedTitle:forgetString forState:UIControlStateNormal];
48 48
49 self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"lifelog.common.back", nil) style:UIBarButtonItemStylePlain target:nil action:nil]; 49 self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"lifelog.common.back", nil) style:UIBarButtonItemStylePlain target:nil action:nil];
50 } 50 }
51 51
52 - (void)didReceiveMemoryWarning { 52 - (void)didReceiveMemoryWarning {
53 [super didReceiveMemoryWarning]; 53 [super didReceiveMemoryWarning];
54 // Dispose of any resources that can be recreated. 54 // Dispose of any resources that can be recreated.
55 } 55 }
56 56
57 - (IBAction)buttonLoginTouchUpInside:(id)sender { 57 - (IBAction)buttonLoginTouchUpInside:(id)sender {
58 LoginViewController __weak *weakSelf = self; 58 LoginViewController __weak *weakSelf = self;
59 [[ServerAPI server] loginWithEmail:_tfEmail.text Password:_tfPassword.text CompletionHandler:^(User *user, NSString *token, NSError *error) { 59 [[ServerAPI server] loginWithEmail:_tfEmail.text Password:_tfPassword.text CompletionHandler:^(User *user, NSString *token, NSError *error) {
60 if (error == nil) { 60 if (error == nil) {
61 // save user and goto MainMenu 61 // save user and goto MainMenu
62 // For Saving
63 NSData *dataSave = [NSKeyedArchiver archivedDataWithRootObject:user];
64 [[NSUserDefaults standardUserDefaults] setObject:dataSave forKey:kUser];
65 [[NSUserDefaults standardUserDefaults] setObject:token forKey:kToken];
66 [[NSUserDefaults standardUserDefaults] synchronize];
62 dispatch_async(dispatch_get_main_queue(), ^{ 67 dispatch_async(dispatch_get_main_queue(), ^{
63 [[AppDelegate sharedAppDelegate] gotoMainMenu]; 68 [[AppDelegate sharedAppDelegate] gotoMainMenu];
64 }); 69 });
65 } 70 }
66 else { 71 else {
67 dispatch_async(dispatch_get_main_queue(), ^{ 72 dispatch_async(dispatch_get_main_queue(), ^{
68 NSString *message = [error.userInfo objectForKey:@"message"]; 73 NSString *message = [error.userInfo objectForKey:@"message"];
69 [Utilities showErrorMessage:message withViewController:weakSelf]; 74 [Utilities showErrorMessage:message withViewController:weakSelf];
70 }); 75 });
71 } 76 }
72 }]; 77 }];
73 } 78 }
74 79
75 - (IBAction)buttonForgetTouchUpInside:(id)sender { 80 - (IBAction)buttonForgetTouchUpInside:(id)sender {
76 if (_tfEmail.text.length > 0) { 81 if (_tfEmail.text.length > 0) {
77 LoginViewController __weak *weakSelf = self; 82 LoginViewController __weak *weakSelf = self;
78 [[ServerAPI server] forgetPass:_tfEmail.text CompletionHandler:^(NSError *error) { 83 [[ServerAPI server] forgetPass:_tfEmail.text CompletionHandler:^(NSError *error) {
79 if (error == nil) { 84 if (error == nil) {
80 // goto screen confirm forgetPass 85 // goto screen confirm forgetPass
81 dispatch_async(dispatch_get_main_queue(), ^{ 86 dispatch_async(dispatch_get_main_queue(), ^{
82 ConfirmForgetPassViewController *confirmVC = [[ConfirmForgetPassViewController alloc] initWithNibName:@"ConfirmForgetPassViewController" bundle:nil]; 87 ConfirmForgetPassViewController *confirmVC = [[ConfirmForgetPassViewController alloc] initWithNibName:@"ConfirmForgetPassViewController" bundle:nil];
83 confirmVC.email = weakSelf.tfEmail.text; 88 confirmVC.email = weakSelf.tfEmail.text;
84 [weakSelf.navigationController pushViewController:confirmVC animated:YES]; 89 [weakSelf.navigationController pushViewController:confirmVC animated:YES];
85 }); 90 });
86 } 91 }
87 else { 92 else {
88 dispatch_async(dispatch_get_main_queue(), ^{ 93 dispatch_async(dispatch_get_main_queue(), ^{
89 NSString *message = [error.userInfo objectForKey:@"message"]; 94 NSString *message = [error.userInfo objectForKey:@"message"];
90 [Utilities showErrorMessage:message withViewController:weakSelf]; 95 [Utilities showErrorMessage:message withViewController:weakSelf];
91 }); 96 });
92 } 97 }
93 }]; 98 }];
94 } 99 }
95 else { 100 else {
96 [Utilities showErrorMessage:@"Please input email" withViewController:self]; 101 [Utilities showErrorMessage:@"Please input email" withViewController:self];
97 } 102 }
98 } 103 }
99 104
100 - (IBAction)buttonRegisterTouchUpInside:(id)sender { 105 - (IBAction)buttonRegisterTouchUpInside:(id)sender {
101 RegisterViewController *registerVC = [[RegisterViewController alloc] initWithNibName:@"RegisterViewController" bundle:nil]; 106 RegisterViewController *registerVC = [[RegisterViewController alloc] initWithNibName:@"RegisterViewController" bundle:nil];
102 [self.navigationController pushViewController:registerVC animated:YES]; 107 [self.navigationController pushViewController:registerVC animated:YES];
103 } 108 }
104 109
105 @end 110 @end
106 111
LifeLog/LifeLog/RegisterViewController.m
1 // 1 //
2 // RegisterViewController.m 2 // RegisterViewController.m
3 // LifeLog 3 // LifeLog
4 // 4 //
5 // Created by Panasonic R&D Center Vietnam on 7/31/17. 5 // Created by Panasonic R&D Center Vietnam on 7/31/17.
6 // Copyright © 2017 PhongNV. All rights reserved. 6 // Copyright © 2017 PhongNV. All rights reserved.
7 // 7 //
8 8
9 #import "RegisterViewController.h" 9 #import "RegisterViewController.h"
10 #import "CustomTextField.h" 10 #import "CustomTextField.h"
11 #import "Utilities.h" 11 #import "Utilities.h"
12 #import "NSDate+helper.h" 12 #import "NSDate+helper.h"
13 #import "ServerAPI.h" 13 #import "ServerAPI.h"
14 #import "AppDelegate.h" 14 #import "AppDelegate.h"
15 static int const kPickerTagArea = 1; 15 static int const kPickerTagArea = 1;
16 static int const kPickerTagSex = 2; 16 static int const kPickerTagSex = 2;
17 17
18 @interface RegisterViewController ()<UIActionSheetDelegate, UINavigationControllerDelegate, UIImagePickerControllerDelegate, UIPickerViewDataSource, UIPickerViewDelegate, UITextFieldDelegate> 18 @interface RegisterViewController ()<UIActionSheetDelegate, UINavigationControllerDelegate, UIImagePickerControllerDelegate, UIPickerViewDataSource, UIPickerViewDelegate, UITextFieldDelegate>
19 { 19 {
20 NSInteger indexArea; 20 NSInteger indexArea;
21 UIPickerView *pickerArea; 21 UIPickerView *pickerArea;
22 22
23 UIPickerView *pickerSex; 23 UIPickerView *pickerSex;
24 UIDatePicker *pickerDate; 24 UIDatePicker *pickerDate;
25 NSDate *dateBirthDay; 25 NSDate *dateBirthDay;
26 NSString *profile_image; 26 NSString *profile_image;
27 } 27 }
28 @property (nonatomic, weak) IBOutlet UIImageView *avatar; 28 @property (nonatomic, weak) IBOutlet UIImageView *avatar;
29 29
30 @property (nonatomic, weak) IBOutlet UILabel *lblUsername; 30 @property (nonatomic, weak) IBOutlet UILabel *lblUsername;
31 @property (nonatomic, weak) IBOutlet UILabel *lblName; 31 @property (nonatomic, weak) IBOutlet UILabel *lblName;
32 @property (nonatomic, weak) IBOutlet UILabel *lblNickname; 32 @property (nonatomic, weak) IBOutlet UILabel *lblNickname;
33 @property (nonatomic, weak) IBOutlet UILabel *lblEmail; 33 @property (nonatomic, weak) IBOutlet UILabel *lblEmail;
34 @property (nonatomic, weak) IBOutlet UILabel *lblPassword; 34 @property (nonatomic, weak) IBOutlet UILabel *lblPassword;
35 @property (nonatomic, weak) IBOutlet UILabel *lblConfirmPassword; 35 @property (nonatomic, weak) IBOutlet UILabel *lblConfirmPassword;
36 @property (nonatomic, weak) IBOutlet UILabel *lblSex; 36 @property (nonatomic, weak) IBOutlet UILabel *lblSex;
37 @property (nonatomic, weak) IBOutlet UILabel *lblBirthday; 37 @property (nonatomic, weak) IBOutlet UILabel *lblBirthday;
38 @property (nonatomic, weak) IBOutlet UILabel *lblHeight; 38 @property (nonatomic, weak) IBOutlet UILabel *lblHeight;
39 @property (nonatomic, weak) IBOutlet UILabel *lblHeightUnit; 39 @property (nonatomic, weak) IBOutlet UILabel *lblHeightUnit;
40 @property (nonatomic, weak) IBOutlet UILabel *lblWeight; 40 @property (nonatomic, weak) IBOutlet UILabel *lblWeight;
41 @property (nonatomic, weak) IBOutlet UILabel *lblWeightUnit; 41 @property (nonatomic, weak) IBOutlet UILabel *lblWeightUnit;
42 @property (nonatomic, weak) IBOutlet UILabel *lblFatPercentage; 42 @property (nonatomic, weak) IBOutlet UILabel *lblFatPercentage;
43 @property (nonatomic, weak) IBOutlet UILabel *lblFatPercentageUnit; 43 @property (nonatomic, weak) IBOutlet UILabel *lblFatPercentageUnit;
44 @property (nonatomic, weak) IBOutlet UILabel *lblPhysicalActivity; 44 @property (nonatomic, weak) IBOutlet UILabel *lblPhysicalActivity;
45 @property (nonatomic, weak) IBOutlet UILabel *lblArea; 45 @property (nonatomic, weak) IBOutlet UILabel *lblArea;
46 @property (nonatomic, weak) IBOutlet UILabel *lblNote; 46 @property (nonatomic, weak) IBOutlet UILabel *lblNote;
47 47
48 @property (nonatomic, weak) IBOutlet UITextField *tfUsername; 48 @property (nonatomic, weak) IBOutlet UITextField *tfUsername;
49 @property (nonatomic, weak) IBOutlet UITextField *tfName; 49 @property (nonatomic, weak) IBOutlet UITextField *tfName;
50 @property (nonatomic, weak) IBOutlet UITextField *tfNickname; 50 @property (nonatomic, weak) IBOutlet UITextField *tfNickname;
51 @property (nonatomic, weak) IBOutlet UITextField *tfEmail; 51 @property (nonatomic, weak) IBOutlet UITextField *tfEmail;
52 @property (nonatomic, weak) IBOutlet UITextField *tfPassword; 52 @property (nonatomic, weak) IBOutlet UITextField *tfPassword;
53 @property (nonatomic, weak) IBOutlet UITextField *tfConfirmPassword; 53 @property (nonatomic, weak) IBOutlet UITextField *tfConfirmPassword;
54 @property (nonatomic, weak) IBOutlet UITextField *tflblSex; 54 @property (nonatomic, weak) IBOutlet UITextField *tflblSex;
55 @property (nonatomic, weak) IBOutlet UITextField *tfBirthday; 55 @property (nonatomic, weak) IBOutlet UITextField *tfBirthday;
56 @property (nonatomic, weak) IBOutlet UITextField *tfHeight; 56 @property (nonatomic, weak) IBOutlet UITextField *tfHeight;
57 @property (nonatomic, weak) IBOutlet UITextField *tfWeight; 57 @property (nonatomic, weak) IBOutlet UITextField *tfWeight;
58 @property (nonatomic, weak) IBOutlet UITextField *tfFatPercentage; 58 @property (nonatomic, weak) IBOutlet UITextField *tfFatPercentage;
59 @property (nonatomic, weak) IBOutlet UISegmentedControl *physicalActivity; 59 @property (nonatomic, weak) IBOutlet UISegmentedControl *physicalActivity;
60 @property (nonatomic, weak) IBOutlet CustomTextField *tfArea; 60 @property (nonatomic, weak) IBOutlet CustomTextField *tfArea;
61 @property (nonatomic, weak) IBOutlet UITextView *tvNote; 61 @property (nonatomic, weak) IBOutlet UITextView *tvNote;
62 62
63 @property (nonatomic, weak) IBOutlet UIToolbar *toolBar; 63 @property (nonatomic, weak) IBOutlet UIToolbar *toolBar;
64 @property (nonatomic, strong) NSArray *arrayArea; 64 @property (nonatomic, strong) NSArray *arrayArea;
65 @property (nonatomic, strong) NSArray *arraySex; 65 @property (nonatomic, strong) NSArray *arraySex;
66 66
67 @property (nonatomic) UIImagePickerController *imagePickerController; 67 @property (nonatomic) UIImagePickerController *imagePickerController;
68 68
69 @end 69 @end
70 70
71 @implementation RegisterViewController 71 @implementation RegisterViewController
72 72
73 - (void)viewDidLoad { 73 - (void)viewDidLoad {
74 [super viewDidLoad]; 74 [super viewDidLoad];
75 [self setupUIRegister]; 75 [self setupUIRegister];
76 76
77 _arrayArea = [[NSArray alloc] initWithObjects:@"北海道", @"青森県", @"岩手県", @"宮城県", @"秋田県", @"山形県", @"福島県", @"茨城県", @"栃木県", @"群馬県", @"埼玉県", @"千葉県", @"東京都", @"神奈川県", @"新潟県", @"富山県", @"石川県", @"福井県", @"山梨県", @"長野県", @"岐阜県", @"静岡県", @"愛知県", @"三重県", @"滋賀県", @"京都府", @"大阪府", @"兵庫県", @"奈良県", @"和歌山県", @"鳥取県", @"島根県", @"岡山県", @"広島県", @"山口県", @"徳島県", @"香川県", @"愛媛県", @"高知県", @"福岡県", @"佐賀県", @"長崎県", @"熊本県", @"大分県" , @"宮崎県", @"鹿児島県", @"沖縄県", nil]; 77 _arrayArea = [[NSArray alloc] initWithObjects:@"北海道", @"青森県", @"岩手県", @"宮城県", @"秋田県", @"山形県", @"福島県", @"茨城県", @"栃木県", @"群馬県", @"埼玉県", @"千葉県", @"東京都", @"神奈川県", @"新潟県", @"富山県", @"石川県", @"福井県", @"山梨県", @"長野県", @"岐阜県", @"静岡県", @"愛知県", @"三重県", @"滋賀県", @"京都府", @"大阪府", @"兵庫県", @"奈良県", @"和歌山県", @"鳥取県", @"島根県", @"岡山県", @"広島県", @"山口県", @"徳島県", @"香川県", @"愛媛県", @"高知県", @"福岡県", @"佐賀県", @"長崎県", @"熊本県", @"大分県" , @"宮崎県", @"鹿児島県", @"沖縄県", nil];
78 _arraySex = [[NSArray alloc] initWithObjects:@"男", @"女", nil]; 78 _arraySex = [[NSArray alloc] initWithObjects:@"男", @"女", nil];
79 79
80 pickerArea = [[UIPickerView alloc] init]; 80 pickerArea = [[UIPickerView alloc] init];
81 pickerArea.dataSource = self; 81 pickerArea.dataSource = self;
82 pickerArea.delegate = self; 82 pickerArea.delegate = self;
83 pickerArea.showsSelectionIndicator = YES; 83 pickerArea.showsSelectionIndicator = YES;
84 pickerArea.tag = kPickerTagArea; 84 pickerArea.tag = kPickerTagArea;
85 pickerArea.backgroundColor = [Utilities convertHecToColor:0x618DB6]; 85 pickerArea.backgroundColor = [Utilities convertHecToColor:0x618DB6];
86 86
87 _tfArea.inputAccessoryView = _toolBar; 87 _tfArea.inputAccessoryView = _toolBar;
88 _tfArea.inputView = pickerArea; 88 _tfArea.inputView = pickerArea;
89 //_tfArea.alpha = 0.5; 89 //_tfArea.alpha = 0.5;
90 _tfArea.delegate = self; 90 _tfArea.delegate = self;
91 91
92 pickerSex = [[UIPickerView alloc] init]; 92 pickerSex = [[UIPickerView alloc] init];
93 pickerSex.dataSource = self; 93 pickerSex.dataSource = self;
94 pickerSex.delegate = self; 94 pickerSex.delegate = self;
95 pickerSex.showsSelectionIndicator = YES; 95 pickerSex.showsSelectionIndicator = YES;
96 pickerSex.tag = kPickerTagSex; 96 pickerSex.tag = kPickerTagSex;
97 pickerSex.backgroundColor = [Utilities convertHecToColor:0x618DB6]; 97 pickerSex.backgroundColor = [Utilities convertHecToColor:0x618DB6];
98 98
99 _tflblSex.inputAccessoryView = _toolBar; 99 _tflblSex.inputAccessoryView = _toolBar;
100 _tflblSex.inputView = pickerSex; 100 _tflblSex.inputView = pickerSex;
101 //_tflblSex.alpha = 0.5; 101 //_tflblSex.alpha = 0.5;
102 _tflblSex.delegate = self; 102 _tflblSex.delegate = self;
103 103
104 pickerDate = [[UIDatePicker alloc] init]; 104 pickerDate = [[UIDatePicker alloc] init];
105 pickerDate.backgroundColor = [Utilities convertHecToColor:0x618DB6]; 105 pickerDate.backgroundColor = [Utilities convertHecToColor:0x618DB6];
106 pickerDate.datePickerMode = UIDatePickerModeDate; 106 pickerDate.datePickerMode = UIDatePickerModeDate;
107 _tfBirthday.inputAccessoryView = _toolBar; 107 _tfBirthday.inputAccessoryView = _toolBar;
108 _tfBirthday.inputView = pickerDate; 108 _tfBirthday.inputView = pickerDate;
109 //_tflblSex.alpha = 0.5; 109 //_tflblSex.alpha = 0.5;
110 _tflblSex.delegate = self; 110 _tflblSex.delegate = self;
111 profile_image = @""; 111 profile_image = @"";
112 } 112 }
113 113
114 - (void)didReceiveMemoryWarning { 114 - (void)didReceiveMemoryWarning {
115 [super didReceiveMemoryWarning]; 115 [super didReceiveMemoryWarning];
116 // Dispose of any resources that can be recreated. 116 // Dispose of any resources that can be recreated.
117 } 117 }
118 118
119 - (void)setupUIRegister 119 - (void)setupUIRegister
120 { 120 {
121 self.avatar.backgroundColor = [UIColor whiteColor]; 121 self.avatar.backgroundColor = [UIColor whiteColor];
122 self.avatar.layer.borderWidth = 2.0f; 122 self.avatar.layer.borderWidth = 2.0f;
123 self.avatar.layer.borderColor = [[UIColor whiteColor] CGColor]; 123 self.avatar.layer.borderColor = [[UIColor whiteColor] CGColor];
124 self.avatar.layer.cornerRadius = self.avatar.frame.size.width/2.0f; 124 self.avatar.layer.cornerRadius = self.avatar.frame.size.width/2.0f;
125 self.avatar.layer.masksToBounds = YES; 125 self.avatar.layer.masksToBounds = YES;
126 self.title = NSLocalizedString(@"lifelog.register.title", nil); 126 self.title = NSLocalizedString(@"lifelog.register.title", nil);
127 self.lblUsername.text = NSLocalizedString(@"lifelog.register.username", nil); 127 self.lblUsername.text = NSLocalizedString(@"lifelog.register.username", nil);
128 self.lblName.text = NSLocalizedString(@"lifelog.register.name", nil); 128 self.lblName.text = NSLocalizedString(@"lifelog.register.name", nil);
129 self.lblNickname.text = NSLocalizedString(@"lifelog.register.nickname", nil); 129 self.lblNickname.text = NSLocalizedString(@"lifelog.register.nickname", nil);
130 self.lblEmail.text = NSLocalizedString(@"lifelog.common.email", nil); 130 self.lblEmail.text = NSLocalizedString(@"lifelog.common.email", nil);
131 self.lblPassword.text = NSLocalizedString(@"lifelog.common.password", nil); 131 self.lblPassword.text = NSLocalizedString(@"lifelog.common.password", nil);
132 self.lblConfirmPassword.text = NSLocalizedString(@"lifelog.register.confirmation.password", nil); 132 self.lblConfirmPassword.text = NSLocalizedString(@"lifelog.register.confirmation.password", nil);
133 self.lblSex.text = NSLocalizedString(@"lifelog.register.sex", nil); 133 self.lblSex.text = NSLocalizedString(@"lifelog.register.sex", nil);
134 self.lblBirthday.text = NSLocalizedString(@"lifelog.register.birthday", nil); 134 self.lblBirthday.text = NSLocalizedString(@"lifelog.register.birthday", nil);
135 self.lblHeight.text = NSLocalizedString(@"lifelog.register.height", nil); 135 self.lblHeight.text = NSLocalizedString(@"lifelog.register.height", nil);
136 self.lblHeightUnit.text = NSLocalizedString(@"lifelog.register.height.unit", nil); 136 self.lblHeightUnit.text = NSLocalizedString(@"lifelog.register.height.unit", nil);
137 self.lblWeight.text = NSLocalizedString(@"lifelog.register.weight", nil); 137 self.lblWeight.text = NSLocalizedString(@"lifelog.register.weight", nil);
138 self.lblWeightUnit.text = NSLocalizedString(@"lifelog.register.weight.unit", nil); 138 self.lblWeightUnit.text = NSLocalizedString(@"lifelog.register.weight.unit", nil);
139 self.lblFatPercentage.text = NSLocalizedString(@"lifelog.register.fat.percentage", nil); 139 self.lblFatPercentage.text = NSLocalizedString(@"lifelog.register.fat.percentage", nil);
140 self.lblFatPercentageUnit.text = NSLocalizedString(@"lifelog.register.fat.percentage.unit", nil); 140 self.lblFatPercentageUnit.text = NSLocalizedString(@"lifelog.register.fat.percentage.unit", nil);
141 self.lblPhysicalActivity.text = NSLocalizedString(@"lifelog.register.daily.physical.activity.level", nil); 141 self.lblPhysicalActivity.text = NSLocalizedString(@"lifelog.register.daily.physical.activity.level", nil);
142 self.lblArea.text = NSLocalizedString(@"lifelog.register.area", nil); 142 self.lblArea.text = NSLocalizedString(@"lifelog.register.area", nil);
143 self.lblNote.text = NSLocalizedString(@"lifelog.register.note", nil); 143 self.lblNote.text = NSLocalizedString(@"lifelog.register.note", nil);
144 144
145 UIImage *img1=[UIImage imageNamed:@"icon_right"]; 145 UIImage *img1=[UIImage imageNamed:@"icon_right"];
146 CGRect frameimg1 = CGRectMake(0, 0, img1.size.width, img1.size.height); 146 CGRect frameimg1 = CGRectMake(0, 0, img1.size.width, img1.size.height);
147 UIButton *registButton=[[UIButton alloc]initWithFrame:frameimg1]; 147 UIButton *registButton=[[UIButton alloc]initWithFrame:frameimg1];
148 [registButton setBackgroundImage:img1 forState:UIControlStateNormal]; 148 [registButton setBackgroundImage:img1 forState:UIControlStateNormal];
149 [registButton addTarget:self action:@selector(registButtonPressed:) 149 [registButton addTarget:self action:@selector(registButtonPressed:)
150 forControlEvents:UIControlEventTouchUpInside]; 150 forControlEvents:UIControlEventTouchUpInside];
151 [registButton setShowsTouchWhenHighlighted:YES]; 151 [registButton setShowsTouchWhenHighlighted:YES];
152 UIBarButtonItem *barButton = [[UIBarButtonItem alloc]initWithCustomView:registButton]; 152 UIBarButtonItem *barButton = [[UIBarButtonItem alloc]initWithCustomView:registButton];
153 self.navigationItem.rightBarButtonItem = barButton; 153 self.navigationItem.rightBarButtonItem = barButton;
154 } 154 }
155 155
156 #pragma mark - Actions 156 #pragma mark - Actions
157 - (IBAction)avatarTouchUpInside:(id)sender { 157 - (IBAction)avatarTouchUpInside:(id)sender {
158 UIActionSheet *action = [[UIActionSheet alloc] initWithTitle:@"Avatar" delegate:self cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles:@"Select Camera", @"Select Photo", nil]; 158 UIActionSheet *action = [[UIActionSheet alloc] initWithTitle:@"Avatar" delegate:self cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles:@"Select Camera", @"Select Photo", nil];
159 [action showInView:self.view]; 159 [action showInView:self.view];
160 } 160 }
161 161
162 - (IBAction)registButtonPressed:(id)sender { 162 - (IBAction)registButtonPressed:(id)sender {
163 if ([self checkAllowRegister]) { 163 if ([self checkAllowRegister]) {
164 [self registerUser]; 164 [self registerUser];
165 } 165 }
166 } 166 }
167 167
168 #pragma mark - UIActionSheetDelegate 168 #pragma mark - UIActionSheetDelegate
169 - (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex { 169 - (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
170 switch (buttonIndex) { 170 switch (buttonIndex) {
171 case 0: 171 case 0:
172 [self showCamera]; 172 [self showCamera];
173 break; 173 break;
174 case 1: 174 case 1:
175 [self showPhoto]; 175 [self showPhoto];
176 break; 176 break;
177 default: 177 default:
178 break; 178 break;
179 } 179 }
180 } 180 }
181 181
182 #pragma mark - UIImagePickerControllerDelegate 182 #pragma mark - UIImagePickerControllerDelegate
183 183
184 // This method is called when an image has been chosen from the library or taken from the camera. 184 // This method is called when an image has been chosen from the library or taken from the camera.
185 - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info 185 - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
186 { 186 {
187 UIImage *image = [info valueForKey:UIImagePickerControllerOriginalImage]; 187 UIImage *image = [info valueForKey:UIImagePickerControllerOriginalImage];
188 //NSData *imageData = UIImageJPEGRepresentation (image, 0.5); 188 //NSData *imageData = UIImageJPEGRepresentation (image, 0.5);
189 189
190 // My image view is 90x90 190 // My image view is 90x90
191 //UIImage *thumbImage = MyCreateThumbnailImageFromData(imageData, 90); 191 //UIImage *thumbImage = MyCreateThumbnailImageFromData(imageData, 90);
192 UIImage *thumbImage = [self imageWithImage:image scaledToFillSize:CGSizeMake(80, 80)]; 192 UIImage *thumbImage = [self imageWithImage:image scaledToFillSize:CGSizeMake(80, 80)];
193 193
194 self.avatar.image = thumbImage; 194 self.avatar.image = thumbImage;
195 NSData *dataImage = UIImagePNGRepresentation(thumbImage); 195 NSData *dataImage = UIImagePNGRepresentation(thumbImage);
196 RegisterViewController __weak *weakSelf = self; 196 RegisterViewController __weak *weakSelf = self;
197 [[ServerAPI server] uploadImage:nil andImageData:dataImage CompletionHandler:^(NSString *linkImage, NSError *error) { 197 [[ServerAPI server] uploadImage:nil andImageData:dataImage CompletionHandler:^(NSString *linkImage, NSError *error) {
198 if (weakSelf == nil) { 198 if (weakSelf == nil) {
199 return ; 199 return ;
200 } 200 }
201 if (error == nil) { 201 if (error == nil) {
202 profile_image = linkImage; 202 profile_image = linkImage;
203 } 203 }
204 else { 204 else {
205 dispatch_async(dispatch_get_main_queue(), ^{ 205 dispatch_async(dispatch_get_main_queue(), ^{
206 NSString *message = [error.userInfo objectForKey:@"message"]; 206 NSString *message = [error.userInfo objectForKey:@"message"];
207 [Utilities showErrorMessage:message withViewController:weakSelf]; 207 [Utilities showErrorMessage:message withViewController:weakSelf];
208 }); 208 });
209 } 209 }
210 }]; 210 }];
211 // Dismiss the image picker. 211 // Dismiss the image picker.
212 [self dismissViewControllerAnimated:YES completion:nil]; 212 [self dismissViewControllerAnimated:YES completion:nil];
213 _imagePickerController = nil; 213 _imagePickerController = nil;
214 } 214 }
215 215
216 - (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker 216 - (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
217 { 217 {
218 [self dismissViewControllerAnimated:YES completion:^{ 218 [self dismissViewControllerAnimated:YES completion:^{
219 //.. done dismissing 219 //.. done dismissing
220 }]; 220 }];
221 } 221 }
222 222
223 - (UIImage *)imageWithImage:(UIImage *)image scaledToFillSize:(CGSize)size 223 - (UIImage *)imageWithImage:(UIImage *)image scaledToFillSize:(CGSize)size
224 { 224 {
225 CGFloat scale = MAX(size.width/image.size.width, size.height/image.size.height); 225 CGFloat scale = MAX(size.width/image.size.width, size.height/image.size.height);
226 CGFloat width = image.size.width * scale; 226 CGFloat width = image.size.width * scale;
227 CGFloat height = image.size.height * scale; 227 CGFloat height = image.size.height * scale;
228 CGRect imageRect = CGRectMake((size.width - width)/2.0f, 228 CGRect imageRect = CGRectMake((size.width - width)/2.0f,
229 (size.height - height)/2.0f, 229 (size.height - height)/2.0f,
230 width, 230 width,
231 height); 231 height);
232 232
233 UIGraphicsBeginImageContextWithOptions(size, NO, 0); 233 UIGraphicsBeginImageContextWithOptions(size, NO, 0);
234 [image drawInRect:imageRect]; 234 [image drawInRect:imageRect];
235 UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext(); 235 UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
236 UIGraphicsEndImageContext(); 236 UIGraphicsEndImageContext();
237 return newImage; 237 return newImage;
238 } 238 }
239 239
240 #pragma mark - Function Private 240 #pragma mark - Function Private
241 - (void)showCamera { 241 - (void)showCamera {
242 if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) 242 if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
243 { 243 {
244 UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init]; 244 UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
245 imagePickerController.modalPresentationStyle = UIModalPresentationCurrentContext; 245 imagePickerController.modalPresentationStyle = UIModalPresentationCurrentContext;
246 imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera; 246 imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
247 imagePickerController.delegate = self; 247 imagePickerController.delegate = self;
248 imagePickerController.modalPresentationStyle = UIModalPresentationFullScreen; 248 imagePickerController.modalPresentationStyle = UIModalPresentationFullScreen;
249 _imagePickerController = imagePickerController; // we need this for later 249 _imagePickerController = imagePickerController; // we need this for later
250 [self presentViewController:self.imagePickerController animated:YES completion:^{ 250 [self presentViewController:self.imagePickerController animated:YES completion:^{
251 //.. done presenting 251 //.. done presenting
252 }]; 252 }];
253 } 253 }
254 } 254 }
255 255
256 - (void)showPhoto { 256 - (void)showPhoto {
257 UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init]; 257 UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
258 imagePickerController.modalPresentationStyle = UIModalPresentationCurrentContext; 258 imagePickerController.modalPresentationStyle = UIModalPresentationCurrentContext;
259 imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary; 259 imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
260 imagePickerController.delegate = self; 260 imagePickerController.delegate = self;
261 imagePickerController.modalPresentationStyle = UIModalPresentationPopover; 261 imagePickerController.modalPresentationStyle = UIModalPresentationPopover;
262 _imagePickerController = imagePickerController; // we need this for later 262 _imagePickerController = imagePickerController; // we need this for later
263 [self presentViewController:self.imagePickerController animated:YES completion:^{ 263 [self presentViewController:self.imagePickerController animated:YES completion:^{
264 //.. done presenting 264 //.. done presenting
265 }]; 265 }];
266 } 266 }
267 267
268 - (void)showImagePickerForSourceType:(UIImagePickerControllerSourceType)sourceType fromButton:(UIBarButtonItem *)button 268 - (void)showImagePickerForSourceType:(UIImagePickerControllerSourceType)sourceType fromButton:(UIBarButtonItem *)button
269 { 269 {
270 if (self.avatar.isAnimating) 270 if (self.avatar.isAnimating)
271 { 271 {
272 [self.avatar stopAnimating]; 272 [self.avatar stopAnimating];
273 } 273 }
274 274
275 UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init]; 275 UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
276 imagePickerController.modalPresentationStyle = UIModalPresentationCurrentContext; 276 imagePickerController.modalPresentationStyle = UIModalPresentationCurrentContext;
277 imagePickerController.sourceType = sourceType; 277 imagePickerController.sourceType = sourceType;
278 imagePickerController.delegate = self; 278 imagePickerController.delegate = self;
279 imagePickerController.modalPresentationStyle = 279 imagePickerController.modalPresentationStyle =
280 (sourceType == UIImagePickerControllerSourceTypeCamera) ? UIModalPresentationFullScreen : UIModalPresentationPopover; 280 (sourceType == UIImagePickerControllerSourceTypeCamera) ? UIModalPresentationFullScreen : UIModalPresentationPopover;
281 281
282 UIPopoverPresentationController *presentationController = imagePickerController.popoverPresentationController; 282 UIPopoverPresentationController *presentationController = imagePickerController.popoverPresentationController;
283 presentationController.barButtonItem = button; // display popover from the UIBarButtonItem as an anchor 283 presentationController.barButtonItem = button; // display popover from the UIBarButtonItem as an anchor
284 presentationController.permittedArrowDirections = UIPopoverArrowDirectionAny; 284 presentationController.permittedArrowDirections = UIPopoverArrowDirectionAny;
285 285
286 if (sourceType == UIImagePickerControllerSourceTypeCamera) 286 if (sourceType == UIImagePickerControllerSourceTypeCamera)
287 { 287 {
288 // The user wants to use the camera interface. Set up our custom overlay view for the camera. 288 // The user wants to use the camera interface. Set up our custom overlay view for the camera.
289 imagePickerController.showsCameraControls = NO; 289 imagePickerController.showsCameraControls = NO;
290 290
291 /* 291 /*
292 Load the overlay view from the OverlayView nib file. Self is the File's Owner for the nib file, so the overlayView outlet is set to the main view in the nib. Pass that view to the image picker controller to use as its overlay view, and set self's reference to the view to nil. 292 Load the overlay view from the OverlayView nib file. Self is the File's Owner for the nib file, so the overlayView outlet is set to the main view in the nib. Pass that view to the image picker controller to use as its overlay view, and set self's reference to the view to nil.
293 */ 293 */
294 } 294 }
295 295
296 _imagePickerController = imagePickerController; // we need this for later 296 _imagePickerController = imagePickerController; // we need this for later
297 297
298 [self presentViewController:self.imagePickerController animated:YES completion:^{ 298 [self presentViewController:self.imagePickerController animated:YES completion:^{
299 //.. done presenting 299 //.. done presenting
300 }]; 300 }];
301 } 301 }
302 302
303 - (IBAction)donePicker:(id)sender 303 - (IBAction)donePicker:(id)sender
304 { 304 {
305 [_tfArea resignFirstResponder]; 305 [_tfArea resignFirstResponder];
306 [_tflblSex resignFirstResponder]; 306 [_tflblSex resignFirstResponder];
307 if ([_tfBirthday becomeFirstResponder]) { 307 if ([_tfBirthday becomeFirstResponder]) {
308 [_tfBirthday resignFirstResponder]; 308 [_tfBirthday resignFirstResponder];
309 dateBirthDay = pickerDate.date; 309 dateBirthDay = pickerDate.date;
310 _tfBirthday.text = [NSString stringWithFormat:@"%ld%@%ld%@%ld%@", (long)[dateBirthDay getYear], NSLocalizedString(@"lifelog.common.year", nil), (long)[dateBirthDay getMonth], NSLocalizedString(@"lifelog.common.month", nil), (long)[dateBirthDay getDay], NSLocalizedString(@"lifelog.common.day", nil)]; 310 _tfBirthday.text = [NSString stringWithFormat:@"%ld%@%ld%@%ld%@", (long)[dateBirthDay getYear], NSLocalizedString(@"lifelog.common.year", nil), (long)[dateBirthDay getMonth], NSLocalizedString(@"lifelog.common.month", nil), (long)[dateBirthDay getDay], NSLocalizedString(@"lifelog.common.day", nil)];
311 } 311 }
312 } 312 }
313 313
314 #pragma mark - UITextFieldDelegate 314 #pragma mark - UITextFieldDelegate
315 - (void)textFieldDidEndEditing:(UITextField *)textField { 315 - (void)textFieldDidEndEditing:(UITextField *)textField {
316 //if (textField == _tfArea) { 316 //if (textField == _tfArea) {
317 [textField resignFirstResponder]; 317 [textField resignFirstResponder];
318 //} 318 //}
319 } 319 }
320 320
321 - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string 321 - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
322 { 322 {
323 //if (textField == _tfArea) { 323 //if (textField == _tfArea) {
324 [textField resignFirstResponder]; 324 [textField resignFirstResponder];
325 return NO; 325 return NO;
326 //} 326 //}
327 //else { 327 //else {
328 return YES; 328 return YES;
329 //} 329 //}
330 } 330 }
331 331
332 - (BOOL)textFieldShouldReturn:(UITextField *)textField 332 - (BOOL)textFieldShouldReturn:(UITextField *)textField
333 { 333 {
334 [textField resignFirstResponder]; 334 [textField resignFirstResponder];
335 return YES; 335 return YES;
336 } 336 }
337 337
338 - (BOOL)textFieldShouldBeginEditing:(UITextField *)textField { 338 - (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
339 //if (textField == _tfArea) { 339 //if (textField == _tfArea) {
340 [textField resignFirstResponder]; 340 [textField resignFirstResponder];
341 //} 341 //}
342 return YES; 342 return YES;
343 } 343 }
344 344
345 - (BOOL)textFieldShouldEndEditing:(UITextField *)textField { 345 - (BOOL)textFieldShouldEndEditing:(UITextField *)textField {
346 //if (textField == _tfArea) { 346 //if (textField == _tfArea) {
347 [textField resignFirstResponder]; 347 [textField resignFirstResponder];
348 //} 348 //}
349 return YES; 349 return YES;
350 } 350 }
351 351
352 #pragma mark - UIPickerViewDataSource 352 #pragma mark - UIPickerViewDataSource
353 353
354 - (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView 354 - (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
355 { 355 {
356 return 1; 356 return 1;
357 } 357 }
358 358
359 - (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component 359 - (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
360 { 360 {
361 int tag = (int)pickerView.tag; 361 int tag = (int)pickerView.tag;
362 switch (tag) { 362 switch (tag) {
363 case kPickerTagArea: 363 case kPickerTagArea:
364 return _arrayArea.count; 364 return _arrayArea.count;
365 case kPickerTagSex: 365 case kPickerTagSex:
366 return _arraySex.count; 366 return _arraySex.count;
367 default: 367 default:
368 return 0; 368 return 0;
369 } 369 }
370 } 370 }
371 371
372 #pragma mark - UIPickerViewDelegate 372 #pragma mark - UIPickerViewDelegate
373 - (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component 373 - (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
374 { 374 {
375 int tag = (int)pickerView.tag; 375 int tag = (int)pickerView.tag;
376 switch (tag) { 376 switch (tag) {
377 case kPickerTagArea: 377 case kPickerTagArea:
378 _tfArea.text = [_arrayArea objectAtIndex:row]; 378 _tfArea.text = [_arrayArea objectAtIndex:row];
379 break; 379 break;
380 case kPickerTagSex: 380 case kPickerTagSex:
381 _tflblSex.text = [_arraySex objectAtIndex:row]; 381 _tflblSex.text = [_arraySex objectAtIndex:row];
382 break; 382 break;
383 default: 383 default:
384 break; 384 break;
385 } 385 }
386 } 386 }
387 387
388 - (NSAttributedString *)pickerView:(UIPickerView *)pickerView attributedTitleForRow:(NSInteger)row forComponent:(NSInteger)component 388 - (NSAttributedString *)pickerView:(UIPickerView *)pickerView attributedTitleForRow:(NSInteger)row forComponent:(NSInteger)component
389 { 389 {
390 NSString *strTitle = @""; 390 NSString *strTitle = @"";
391 int tag = (int)pickerView.tag; 391 int tag = (int)pickerView.tag;
392 switch (tag) { 392 switch (tag) {
393 case kPickerTagArea: 393 case kPickerTagArea:
394 strTitle = [_arrayArea objectAtIndex:row]; 394 strTitle = [_arrayArea objectAtIndex:row];
395 break; 395 break;
396 case kPickerTagSex: 396 case kPickerTagSex:
397 strTitle = [_arraySex objectAtIndex:row]; 397 strTitle = [_arraySex objectAtIndex:row];
398 break; 398 break;
399 default: 399 default:
400 strTitle = @""; 400 strTitle = @"";
401 break; 401 break;
402 } 402 }
403 NSAttributedString *attString = [[NSAttributedString alloc] initWithString:strTitle attributes:@{NSForegroundColorAttributeName:[UIColor whiteColor]}]; 403 NSAttributedString *attString = [[NSAttributedString alloc] initWithString:strTitle attributes:@{NSForegroundColorAttributeName:[UIColor whiteColor]}];
404 404
405 return attString; 405 return attString;
406 406
407 } 407 }
408 408
409 - (NSMutableDictionary *)addParam:(NSString *)param value:(NSString *)value withDict:(NSMutableDictionary *)dict 409 - (NSMutableDictionary *)addParam:(NSString *)param value:(NSString *)value withDict:(NSMutableDictionary *)dict
410 { 410 {
411 if (value.length > 0) { 411 if (value.length > 0) {
412 [dict setObject:value forKey:param]; 412 [dict setObject:value forKey:param];
413 } 413 }
414 return dict; 414 return dict;
415 } 415 }
416 416
417 - (BOOL)checkAllowRegister 417 - (BOOL)checkAllowRegister
418 { 418 {
419 NSString *message = @""; 419 NSString *message = @"";
420 if (_tfUsername.text.length <= 0) { 420 if (_tfUsername.text.length <= 0) {
421 message = @"Please input username"; 421 message = @"Please input username";
422 [Utilities showErrorMessage:message withViewController:self]; 422 [Utilities showErrorMessage:message withViewController:self];
423 return NO; 423 return NO;
424 } 424 }
425 if (_tfName.text.length <= 0) { 425 if (_tfName.text.length <= 0) {
426 message = @"Please input full name"; 426 message = @"Please input full name";
427 [Utilities showErrorMessage:message withViewController:self]; 427 [Utilities showErrorMessage:message withViewController:self];
428 return NO; 428 return NO;
429 } 429 }
430 if (_tfEmail.text.length <= 0) { 430 if (_tfEmail.text.length <= 0) {
431 message = @"Please input email"; 431 message = @"Please input email";
432 [Utilities showErrorMessage:message withViewController:self]; 432 [Utilities showErrorMessage:message withViewController:self];
433 return NO; 433 return NO;
434 } 434 }
435 if (_tfPassword.text.length <= 0) { 435 if (_tfPassword.text.length <= 0) {
436 message = @"Please input password"; 436 message = @"Please input password";
437 [Utilities showErrorMessage:message withViewController:self]; 437 [Utilities showErrorMessage:message withViewController:self];
438 return NO; 438 return NO;
439 } 439 }
440 if (_tfConfirmPassword.text.length <= 0) { 440 if (_tfConfirmPassword.text.length <= 0) {
441 message = @"Please input confirm password"; 441 message = @"Please input confirm password";
442 [Utilities showErrorMessage:message withViewController:self]; 442 [Utilities showErrorMessage:message withViewController:self];
443 return NO; 443 return NO;
444 } 444 }
445 if (_tflblSex.text.length <= 0) { 445 if (_tflblSex.text.length <= 0) {
446 message = @"Please input gender"; 446 message = @"Please input gender";
447 [Utilities showErrorMessage:message withViewController:self]; 447 [Utilities showErrorMessage:message withViewController:self];
448 return NO; 448 return NO;
449 } 449 }
450 if (_tfUsername.text.length > 100) { 450 if (_tfUsername.text.length > 100) {
451 message = @"Username maximum length 100"; 451 message = @"Username maximum length 100";
452 [Utilities showErrorMessage:message withViewController:self]; 452 [Utilities showErrorMessage:message withViewController:self];
453 return NO; 453 return NO;
454 } 454 }
455 if (_tfName.text.length > 255) { 455 if (_tfName.text.length > 255) {
456 message = @"Full name maximum length 255"; 456 message = @"Full name maximum length 255";
457 [Utilities showErrorMessage:message withViewController:self]; 457 [Utilities showErrorMessage:message withViewController:self];
458 return NO; 458 return NO;
459 } 459 }
460 if (_tfEmail.text.length > 255) { 460 if (_tfEmail.text.length > 255) {
461 message = @"Email maximum length 255"; 461 message = @"Email maximum length 255";
462 [Utilities showErrorMessage:message withViewController:self]; 462 [Utilities showErrorMessage:message withViewController:self];
463 return NO; 463 return NO;
464 } 464 }
465 if (_tfPassword.text.length < 6) { 465 if (_tfPassword.text.length < 6) {
466 message = @"Password minimum length 6"; 466 message = @"Password minimum length 6";
467 [Utilities showErrorMessage:message withViewController:self]; 467 [Utilities showErrorMessage:message withViewController:self];
468 return NO; 468 return NO;
469 } 469 }
470 if (![_tfEmail.text containsString:@"@"]) { 470 if (![_tfEmail.text containsString:@"@"]) {
471 message = @"Email invalid"; 471 message = @"Email invalid";
472 [Utilities showErrorMessage:message withViewController:self]; 472 [Utilities showErrorMessage:message withViewController:self];
473 return NO; 473 return NO;
474 } 474 }
475 return YES; 475 return YES;
476 } 476 }
477 477
478 - (NSDictionary *)createParamsForRegisterUser { 478 - (NSDictionary *)createParamsForRegisterUser {
479 NSMutableDictionary *dictResutl = [[NSMutableDictionary alloc] init]; 479 NSMutableDictionary *dictResutl = [[NSMutableDictionary alloc] init];
480 dictResutl = [self addParam:@"username" value:_tfUsername.text withDict:dictResutl]; 480 dictResutl = [self addParam:@"username" value:_tfUsername.text withDict:dictResutl];
481 dictResutl = [self addParam:@"full_name" value:_tfName.text withDict:dictResutl]; 481 dictResutl = [self addParam:@"full_name" value:_tfName.text withDict:dictResutl];
482 dictResutl = [self addParam:@"nickname" value:_tfNickname.text withDict:dictResutl]; 482 dictResutl = [self addParam:@"nickname" value:_tfNickname.text withDict:dictResutl];
483 dictResutl = [self addParam:@"email" value:_tfEmail.text withDict:dictResutl]; 483 dictResutl = [self addParam:@"email" value:_tfEmail.text withDict:dictResutl];
484 dictResutl = [self addParam:@"password" value:_tfPassword.text withDict:dictResutl]; 484 dictResutl = [self addParam:@"password" value:_tfPassword.text withDict:dictResutl];
485 dictResutl = [self addParam:@"password_confirmation" value:_tfConfirmPassword.text withDict:dictResutl]; 485 dictResutl = [self addParam:@"password_confirmation" value:_tfConfirmPassword.text withDict:dictResutl];
486 // 0 - 男, 1 - 女 // NSString *valueSex = nil; 486 // 0 - 男, 1 - 女 // NSString *valueSex = nil;
487 if (_tflblSex.text.length > 0) { 487 if (_tflblSex.text.length > 0) {
488 if ([_tflblSex.text isEqualToString:@"男"]) { 488 if ([_tflblSex.text isEqualToString:@"男"]) {
489 [dictResutl setValue:[NSNumber numberWithInt:0] forKey:@"gender"]; 489 [dictResutl setValue:[NSNumber numberWithInt:0] forKey:@"gender"];
490 } 490 }
491 else if ([_tflblSex.text isEqualToString:@"女"]) { 491 else if ([_tflblSex.text isEqualToString:@"女"]) {
492 [dictResutl setValue:[NSNumber numberWithInt:1] forKey:@"gender"]; 492 [dictResutl setValue:[NSNumber numberWithInt:1] forKey:@"gender"];
493 } 493 }
494 } 494 }
495 //dictResutl = [self addParam:@"gender" value:valueSex withDict:dictResutl]; 495 //dictResutl = [self addParam:@"gender" value:valueSex withDict:dictResutl];
496 NSString *valueBirthDay = nil; 496 NSString *valueBirthDay = nil;
497 if (_tfBirthday.text.length > 0) { 497 if (_tfBirthday.text.length > 0) {
498 NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 498 NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
499 [dateFormatter setDateFormat:@"yyyy-MM-dd"]; 499 [dateFormatter setDateFormat:@"yyyy-MM-dd"];
500 valueBirthDay = [dateFormatter stringFromDate:dateBirthDay]; 500 valueBirthDay = [dateFormatter stringFromDate:dateBirthDay];
501 //valueBirthDay = [NSString stringWithFormat:@"%ld-%ld-%ld", (long)[dateBirthDay getYear], (long)[dateBirthDay getMonth], (long)[dateBirthDay getDay]]; 501 //valueBirthDay = [NSString stringWithFormat:@"%ld-%ld-%ld", (long)[dateBirthDay getYear], (long)[dateBirthDay getMonth], (long)[dateBirthDay getDay]];
502 dictResutl = [self addParam:@"birthday" value:valueBirthDay withDict:dictResutl]; 502 dictResutl = [self addParam:@"birthday" value:valueBirthDay withDict:dictResutl];
503 } 503 }
504 dictResutl = [self addParam:@"height" value:_tfHeight.text withDict:dictResutl]; 504 dictResutl = [self addParam:@"height" value:_tfHeight.text withDict:dictResutl];
505 dictResutl = [self addParam:@"weight" value:_tfWeight.text withDict:dictResutl]; 505 dictResutl = [self addParam:@"weight" value:_tfWeight.text withDict:dictResutl];
506 dictResutl = [self addParam:@"fat_rate" value:_tfFatPercentage.text withDict:dictResutl]; 506 dictResutl = [self addParam:@"fat_rate" value:_tfFatPercentage.text withDict:dictResutl];
507 NSString *physicalActivityValue = [NSString stringWithFormat:@"%ld", _physicalActivity.selectedSegmentIndex]; 507 NSString *physicalActivityValue = [NSString stringWithFormat:@"%ld", _physicalActivity.selectedSegmentIndex];
508 dictResutl = [self addParam:@"physical_activity" value:physicalActivityValue withDict:dictResutl]; 508 dictResutl = [self addParam:@"physical_activity" value:physicalActivityValue withDict:dictResutl];
509 dictResutl = [self addParam:@"address" value:_tfArea.text withDict:dictResutl]; 509 dictResutl = [self addParam:@"address" value:_tfArea.text withDict:dictResutl];
510 dictResutl = [self addParam:@"description" value:_tvNote.text withDict:dictResutl]; 510 dictResutl = [self addParam:@"description" value:_tvNote.text withDict:dictResutl];
511 if (![profile_image isEqualToString:@""]) { 511 if (![profile_image isEqualToString:@""]) {
512 dictResutl = [self addParam:@"profile_image" value:profile_image withDict:dictResutl]; 512 dictResutl = [self addParam:@"profile_image" value:profile_image withDict:dictResutl];
513 } 513 }
514 // hardcode 514 // hardcode
515 // require 515 // require
516 [dictResutl setValue:[NSNumber numberWithInt:0] forKey:@"receive_notification"]; 516 [dictResutl setValue:[NSNumber numberWithInt:0] forKey:@"receive_notification"];
517 // = [self addParam:@"receive_notification" value:@"0" withDict:dictResutl]; 517 // = [self addParam:@"receive_notification" value:@"0" withDict:dictResutl];
518 [dictResutl setValue:[NSNumber numberWithInt:0] forKey:@"share_data"]; 518 [dictResutl setValue:[NSNumber numberWithInt:0] forKey:@"share_data"];
519 // dictResutl = [self addParam:@"share_data" value:@"0" withDict:dictResutl]; 519 // dictResutl = [self addParam:@"share_data" value:@"0" withDict:dictResutl];
520 520
521 // Option 521 // Option
522 //dictResutl = [self addParam:@"phone" value:@"01676582596" withDict:dictResutl]; 522 //dictResutl = [self addParam:@"phone" value:@"01676582596" withDict:dictResutl];
523 [dictResutl setValue:[NSNumber numberWithInt:0] forKey:@"remember"]; 523 [dictResutl setValue:[NSNumber numberWithInt:0] forKey:@"remember"];
524 //dictResutl = [self addParam:@"remember" value:@"0" withDict:dictResutl]; 524 //dictResutl = [self addParam:@"remember" value:@"0" withDict:dictResutl];
525 525
526 return dictResutl; 526 return dictResutl;
527 } 527 }
528 528
529 - (void)registerUser { 529 - (void)registerUser {
530 NSDictionary *paramRegister = [self createParamsForRegisterUser]; 530 NSDictionary *paramRegister = [self createParamsForRegisterUser];
531 RegisterViewController __weak *weakSelf = self; 531 RegisterViewController __weak *weakSelf = self;
532 [[ServerAPI server] registerUserWithParams:paramRegister CompletionHandler:^(User *user, NSString *token, NSError *error) { 532 [[ServerAPI server] registerUserWithParams:paramRegister CompletionHandler:^(User *user, NSString *token, NSError *error) {
533 if (weakSelf == nil) { 533 if (weakSelf == nil) {
534 return ; 534 return ;
535 } 535 }
536 if (error == nil) { 536 if (error == nil) {
537 // For Saving
538 NSData *dataSave = [NSKeyedArchiver archivedDataWithRootObject:user];
539 [[NSUserDefaults standardUserDefaults] setObject:dataSave forKey:kUser];
540 [[NSUserDefaults standardUserDefaults] setObject:token forKey:kToken];
541 [[NSUserDefaults standardUserDefaults] synchronize];
537 dispatch_async(dispatch_get_main_queue(), ^{ 542 dispatch_async(dispatch_get_main_queue(), ^{
538 [[AppDelegate sharedAppDelegate] gotoMainMenu]; 543 [[AppDelegate sharedAppDelegate] gotoMainMenu];
539 }); 544 });
540 } 545 }
541 else { 546 else {
542 dispatch_async(dispatch_get_main_queue(), ^{ 547 dispatch_async(dispatch_get_main_queue(), ^{
543 NSString *message = [error.userInfo objectForKey:@"message"]; 548 NSString *message = [error.userInfo objectForKey:@"message"];
544 [Utilities showErrorMessage:message withViewController:weakSelf]; 549 [Utilities showErrorMessage:message withViewController:weakSelf];
545 }); 550 });
546 } 551 }
547 }]; 552 }];
548 } 553 }
549 554
550 @end 555 @end
551 556
LifeLog/LifeLog/ServerAPI.h
1 // 1 //
2 // ServerAPI.h 2 // ServerAPI.h
3 // LifeLog 3 // LifeLog
4 // 4 //
5 // Created by Nguyen Van Phong on 7/30/17. 5 // Created by Nguyen Van Phong on 7/30/17.
6 // Copyright © 2017 PhongNV. All rights reserved. 6 // Copyright © 2017 PhongNV. All rights reserved.
7 // 7 //
8 8
9 #import <Foundation/Foundation.h> 9 #import <Foundation/Foundation.h>
10 #import "Entities.h" 10 #import "Entities.h"
11 extern NSString *const kServerAddress;
12 extern NSString *const kUser;
13 extern NSString *const kToken;
11 14
12 @interface ServerAPI : NSObject 15 @interface ServerAPI : NSObject
13 + (instancetype) server; 16 + (instancetype) server;
14 @property (nonatomic, assign) NSTimeInterval timeOutInterval; 17 @property (nonatomic, assign) NSTimeInterval timeOutInterval;
15 - (void)loginWithEmail:(NSString *)email Password:(NSString *)password CompletionHandler: (void (^)(User *, NSString *, NSError *)) completion; 18 - (void)loginWithEmail:(NSString *)email Password:(NSString *)password CompletionHandler: (void (^)(User *, NSString *, NSError *)) completion;
16 - (void)registerUserWithParams:(NSDictionary *)params CompletionHandler: (void (^)(User *, NSString *, NSError *)) completion; 19 - (void)registerUserWithParams:(NSDictionary *)params CompletionHandler: (void (^)(User *, NSString *, NSError *)) completion;
17 - (void)uploadImage:(NSString *)token andImageData:(NSData *)data CompletionHandler:(void (^)(NSString *, NSError *)) completion; 20 - (void)uploadImage:(NSString *)token andImageData:(NSData *)data CompletionHandler:(void (^)(NSString *, NSError *)) completion;
18 - (void)forgetPass:(NSString *)email CompletionHandler:(void (^)(NSError *)) completion; 21 - (void)forgetPass:(NSString *)email CompletionHandler:(void (^)(NSError *)) completion;
19 - (void)confirmForgetPass:(NSString *)email withConfirm:(NSString *)confirm CompletionHandler:(void (^)(NSError *)) completion; 22 - (void)confirmForgetPass:(NSString *)email withConfirm:(NSString *)confirm CompletionHandler:(void (^)(NSError *)) completion;
20 @end 23 @end
21 24
LifeLog/LifeLog/ServerAPI.m
1 // 1 //
2 // ServerAPI.m 2 // ServerAPI.m
3 // LifeLog 3 // LifeLog
4 // 4 //
5 // Created by Nguyen Van Phong on 7/30/17. 5 // Created by Nguyen Van Phong on 7/30/17.
6 // Copyright © 2017 PhongNV. All rights reserved. 6 // Copyright © 2017 PhongNV. All rights reserved.
7 // 7 //
8 8
9 #import "ServerAPI.h" 9 #import "ServerAPI.h"
10 10
11 NSString *const kServerAddress = @"http://clover.timesfun.jp:9001/"; 11 NSString *const kServerAddress = @"http://clover.timesfun.jp:9001/";
12 NSString *const kUser = @"KEY_USER";
13 NSString *const kToken = @"KEY_TOKEN";
12 14
13 @implementation NSString (NSString_Extended) 15 @implementation NSString (NSString_Extended)
14 - (NSString *)urlencode { 16 - (NSString *)urlencode {
15 NSMutableString *output = [NSMutableString string]; 17 NSMutableString *output = [NSMutableString string];
16 const unsigned char *source = (const unsigned char *)[self UTF8String]; 18 const unsigned char *source = (const unsigned char *)[self UTF8String];
17 int sourceLen = (int)strlen((const char *)source); 19 int sourceLen = (int)strlen((const char *)source);
18 for (int i = 0; i < sourceLen; ++i) { 20 for (int i = 0; i < sourceLen; ++i) {
19 const unsigned char thisChar = source[i]; 21 const unsigned char thisChar = source[i];
20 if (thisChar == ' '){ 22 if (thisChar == ' '){
21 [output appendString:@"+"]; 23 [output appendString:@"+"];
22 } else if (thisChar == '.' || thisChar == '-' || thisChar == '_' || thisChar == '~' || 24 } else if (thisChar == '.' || thisChar == '-' || thisChar == '_' || thisChar == '~' ||
23 (thisChar >= 'a' && thisChar <= 'z') || 25 (thisChar >= 'a' && thisChar <= 'z') ||
24 (thisChar >= 'A' && thisChar <= 'Z') || 26 (thisChar >= 'A' && thisChar <= 'Z') ||
25 (thisChar >= '0' && thisChar <= '9')) { 27 (thisChar >= '0' && thisChar <= '9')) {
26 [output appendFormat:@"%c", thisChar]; 28 [output appendFormat:@"%c", thisChar];
27 } else { 29 } else {
28 [output appendFormat:@"%%%02X", thisChar]; 30 [output appendFormat:@"%%%02X", thisChar];
29 } 31 }
30 } 32 }
31 return output; 33 return output;
32 } 34 }
33 @end 35 @end
34 36
35 @implementation ServerAPI 37 @implementation ServerAPI
36 static ServerAPI *_server = nil; 38 static ServerAPI *_server = nil;
37 39
38 @synthesize timeOutInterval = _timeOutInterval; 40 @synthesize timeOutInterval = _timeOutInterval;
39 41
40 + (instancetype)server 42 + (instancetype)server
41 { 43 {
42 @synchronized(self) { 44 @synchronized(self) {
43 if (_server == nil) { 45 if (_server == nil) {
44 _server = [[ServerAPI alloc] init]; 46 _server = [[ServerAPI alloc] init];
45 } 47 }
46 } 48 }
47 return _server; 49 return _server;
48 } 50 }
49 51
50 - (instancetype)init 52 - (instancetype)init
51 { 53 {
52 self = [super init]; 54 self = [super init];
53 if (self != nil) { 55 if (self != nil) {
54 self.timeOutInterval = 150; 56 self.timeOutInterval = 150;
55 } 57 }
56 return self; 58 return self;
57 } 59 }
58 60
59 // Login 61 // Login
60 - (void)loginWithEmail:(NSString *)email Password:(NSString *)password CompletionHandler: (void (^)(User *, NSString *, NSError *)) completion 62 - (void)loginWithEmail:(NSString *)email Password:(NSString *)password CompletionHandler: (void (^)(User *, NSString *, NSError *)) completion
61 { 63 {
62 [self _request:[kServerAddress stringByAppendingFormat: @"login"] method:@"POST" paras:@{@"email":email, @"password": password} completion:^(NSData *data, NSError *error) { 64 [self _request:[kServerAddress stringByAppendingFormat: @"login"] method:@"POST" paras:@{@"email":email, @"password": password} completion:^(NSData *data, NSError *error) {
63 65
64 if (completion == NULL) { 66 if (completion == NULL) {
65 return ; 67 return ;
66 } 68 }
67 69
68 if (error == nil) 70 if (error == nil)
69 { 71 {
70 NSDictionary *dataResult = [NSJSONSerialization JSONObjectWithData:data options: NSJSONReadingAllowFragments error: &error]; 72 NSDictionary *dataResult = [NSJSONSerialization JSONObjectWithData:data options: NSJSONReadingAllowFragments error: &error];
71 73
72 int status = [dataResult[@"status"] intValue]; 74 int status = [dataResult[@"status"] intValue];
73 if (status == 1) { // status = 1 success 75 if (status == 1) { // status = 1 success
74 NSString *token = dataResult[@"result"][@"token"]; 76 NSString *token = dataResult[@"result"][@"token"];
75 NSDictionary *dictUser = dataResult[@"result"][@"user"]; 77 NSDictionary *dictUser = dataResult[@"result"][@"user"];
76 User *user = [[User alloc] init]; 78 User *user = [[User alloc] init];
77 user.user_id = [NSString stringWithFormat:@"%@",dictUser[@"id"]]; 79 user.user_id = [NSString stringWithFormat:@"%@",dictUser[@"id"]];
78 user.username = [NSString stringWithFormat:@"%@",dictUser[@"username"]]; 80 user.username = [NSString stringWithFormat:@"%@",dictUser[@"username"]];
79 user.full_name = [NSString stringWithFormat:@"%@",dictUser[@"full_name"]]; 81 user.full_name = [NSString stringWithFormat:@"%@",dictUser[@"full_name"]];
80 user.nickname = [NSString stringWithFormat:@"%@",dictUser[@"nickname"]]; 82 user.nickname = [NSString stringWithFormat:@"%@",dictUser[@"nickname"]];
81 user.email = [NSString stringWithFormat:@"%@",dictUser[@"email"]]; 83 user.email = [NSString stringWithFormat:@"%@",dictUser[@"email"]];
82 user.password = [NSString stringWithFormat:@"%@",dictUser[@"password"]]; 84 user.password = [NSString stringWithFormat:@"%@",dictUser[@"password"]];
83 user.birthday = [NSString stringWithFormat:@"%@",dictUser[@"birthday"]]; 85 user.birthday = [NSString stringWithFormat:@"%@",dictUser[@"birthday"]];
84 user.address = [NSString stringWithFormat:@"%@",dictUser[@"address"]]; 86 user.address = [NSString stringWithFormat:@"%@",dictUser[@"address"]];
85 user.gender = [[NSString stringWithFormat:@"%@",dictUser[@"gender"]] intValue]; 87 user.gender = [[NSString stringWithFormat:@"%@",dictUser[@"gender"]] intValue];
86 user.height = [[NSString stringWithFormat:@"%@",dictUser[@"height"]] floatValue]; 88 user.height = [[NSString stringWithFormat:@"%@",dictUser[@"height"]] floatValue];
87 user.weight = [[NSString stringWithFormat:@"%@",dictUser[@"weight"]] floatValue]; 89 user.weight = [[NSString stringWithFormat:@"%@",dictUser[@"weight"]] floatValue];
88 user.user_description = [NSString stringWithFormat:@"%@",dictUser[@"description"]]; 90 user.user_description = [NSString stringWithFormat:@"%@",dictUser[@"description"]];
91 user.created_at = [NSString stringWithFormat:@"%@",dictUser[@"created_at"]];
92 user.physical_activity = [NSString stringWithFormat:@"%@",dictUser[@"physical_activity"]];
93 user.profile_image = [NSString stringWithFormat:@"%@",dictUser[@"profile_image"]];
94 user.updated_at = [NSString stringWithFormat:@"%@",dictUser[@"updated_at"]];
95 user.delete_flag = [[NSString stringWithFormat:@"%@",dictUser[@"delete_flag"]] intValue];
96 user.fat_rate = [[NSString stringWithFormat:@"%@",dictUser[@"fat_rate"]] intValue];
97 user.profiles_share = [[NSString stringWithFormat:@"%@",dictUser[@"profiles_share"]] intValue];
98 user.remember_me = [[NSString stringWithFormat:@"%@",dictUser[@"remember_me"]] intValue];
99 user.sound_notifications_share = [[NSString stringWithFormat:@"%@",dictUser[@"sound_notifications_share"]] intValue];
100 user.spend_calo_in_day = [[NSString stringWithFormat:@"%@",dictUser[@"spend_calo_in_day"]] intValue];
101 user.target = [[NSString stringWithFormat:@"%@",dictUser[@"target"]] intValue];
89 completion(user, token, nil); 102 completion(user, token, nil);
90 } 103 }
91 else { // status = 0 error 104 else { // status = 0 error
92 NSString *message = dataResult[@"message"]; 105 NSString *message = dataResult[@"message"];
93 NSError *loginFaild = [NSError errorWithDomain:@"LifeLog_Domain" code:-1 userInfo:@{@"message":message}]; 106 NSError *loginFaild = [NSError errorWithDomain:@"LifeLog_Domain" code:-1 userInfo:@{@"message":message}];
94 completion(nil, nil, loginFaild); 107 completion(nil, nil, loginFaild);
95 } 108 }
96 } 109 }
97 else 110 else
98 { 111 {
99 completion(nil, nil, error); 112 completion(nil, nil, error);
100 } 113 }
101 }]; 114 }];
102 } 115 }
103 116
104 // Register 117 // Register
105 - (void)registerUserWithParams:(NSDictionary *)params CompletionHandler: (void (^)(User *, NSString *, NSError *)) completion { 118 - (void)registerUserWithParams:(NSDictionary *)params CompletionHandler: (void (^)(User *, NSString *, NSError *)) completion {
106 [self _request:[kServerAddress stringByAppendingFormat: @"register"] method:@"POST" paras:params completion:^(NSData *data, NSError *error) { 119 [self _request:[kServerAddress stringByAppendingFormat: @"register"] method:@"POST" paras:params completion:^(NSData *data, NSError *error) {
107 120
108 if (completion == NULL) { 121 if (completion == NULL) {
109 return ; 122 return ;
110 } 123 }
111 124
112 if (error == nil) 125 if (error == nil)
113 { 126 {
114 NSDictionary *dataResult = [NSJSONSerialization JSONObjectWithData:data options: NSJSONReadingAllowFragments error: &error]; 127 NSDictionary *dataResult = [NSJSONSerialization JSONObjectWithData:data options: NSJSONReadingAllowFragments error: &error];
115 128
116 int status = [dataResult[@"status"] intValue]; 129 int status = [dataResult[@"status"] intValue];
117 if (status == 1) { // status = 1 success 130 if (status == 1) { // status = 1 success
118 NSString *token = dataResult[@"result"][@"token"]; 131 NSString *token = dataResult[@"result"][@"token"];
119 NSDictionary *dictUser = dataResult[@"result"][@"user"]; 132 NSDictionary *dictUser = dataResult[@"result"][@"user"];
120 User *user = [[User alloc] init]; 133 User *user = [[User alloc] init];
121 user.user_id = [NSString stringWithFormat:@"%@",dictUser[@"id"]]; 134 user.user_id = [NSString stringWithFormat:@"%@",dictUser[@"id"]];
122 user.username = [NSString stringWithFormat:@"%@",dictUser[@"username"]]; 135 user.username = [NSString stringWithFormat:@"%@",dictUser[@"username"]];
123 user.full_name = [NSString stringWithFormat:@"%@",dictUser[@"full_name"]]; 136 user.full_name = [NSString stringWithFormat:@"%@",dictUser[@"full_name"]];
124 user.nickname = [NSString stringWithFormat:@"%@",dictUser[@"nickname"]]; 137 user.nickname = [NSString stringWithFormat:@"%@",dictUser[@"nickname"]];
125 user.email = [NSString stringWithFormat:@"%@",dictUser[@"email"]]; 138 user.email = [NSString stringWithFormat:@"%@",dictUser[@"email"]];
126 user.password = [NSString stringWithFormat:@"%@",dictUser[@"password"]]; 139 user.password = [NSString stringWithFormat:@"%@",dictUser[@"password"]];
127 user.birthday = [NSString stringWithFormat:@"%@",dictUser[@"birthday"]]; 140 user.birthday = [NSString stringWithFormat:@"%@",dictUser[@"birthday"]];
128 user.address = [NSString stringWithFormat:@"%@",dictUser[@"address"]]; 141 user.address = [NSString stringWithFormat:@"%@",dictUser[@"address"]];
129 user.gender = [[NSString stringWithFormat:@"%@",dictUser[@"gender"]] intValue]; 142 user.gender = [[NSString stringWithFormat:@"%@",dictUser[@"gender"]] intValue];
130 user.height = [[NSString stringWithFormat:@"%@",dictUser[@"height"]] floatValue]; 143 user.height = [[NSString stringWithFormat:@"%@",dictUser[@"height"]] floatValue];
131 user.weight = [[NSString stringWithFormat:@"%@",dictUser[@"weight"]] floatValue]; 144 user.weight = [[NSString stringWithFormat:@"%@",dictUser[@"weight"]] floatValue];
132 user.user_description = [NSString stringWithFormat:@"%@",dictUser[@"description"]]; 145 user.user_description = [NSString stringWithFormat:@"%@",dictUser[@"description"]];
146 user.created_at = [NSString stringWithFormat:@"%@",dictUser[@"created_at"]];
147 user.physical_activity = [NSString stringWithFormat:@"%@",dictUser[@"physical_activity"]];
148 user.profile_image = [NSString stringWithFormat:@"%@",dictUser[@"profile_image"]];
149 user.updated_at = [NSString stringWithFormat:@"%@",dictUser[@"updated_at"]];
150 user.delete_flag = [[NSString stringWithFormat:@"%@",dictUser[@"delete_flag"]] intValue];
151 user.fat_rate = [[NSString stringWithFormat:@"%@",dictUser[@"fat_rate"]] intValue];
152 user.profiles_share = [[NSString stringWithFormat:@"%@",dictUser[@"profiles_share"]] intValue];
153 user.remember_me = [[NSString stringWithFormat:@"%@",dictUser[@"remember_me"]] intValue];
154 user.sound_notifications_share = [[NSString stringWithFormat:@"%@",dictUser[@"sound_notifications_share"]] intValue];
155 user.spend_calo_in_day = [[NSString stringWithFormat:@"%@",dictUser[@"spend_calo_in_day"]] intValue];
156 user.target = [[NSString stringWithFormat:@"%@",dictUser[@"target"]] intValue];
133 completion(user, token, nil); 157 completion(user, token, nil);
134 } 158 }
135 else { // status = 0 error 159 else { // status = 0 error
136 NSString *message = dataResult[@"message"]; 160 NSString *message = dataResult[@"message"];
137 NSError *loginFaild = [NSError errorWithDomain:@"LifeLog_Domain" code:-1 userInfo:@{@"message":message}]; 161 NSError *loginFaild = [NSError errorWithDomain:@"LifeLog_Domain" code:-1 userInfo:@{@"message":message}];
138 completion(nil, nil, loginFaild); 162 completion(nil, nil, loginFaild);
139 } 163 }
140 } 164 }
141 else 165 else
142 { 166 {
143 completion(nil, nil, error); 167 completion(nil, nil, error);
144 } 168 }
145 }]; 169 }];
146 } 170 }
147 171
148 - (void)forgetPass:(NSString *)email CompletionHandler:(void (^)(NSError *)) completion { 172 - (void)forgetPass:(NSString *)email CompletionHandler:(void (^)(NSError *)) completion {
149 [self _request:[kServerAddress stringByAppendingFormat: @"forgetPass"] method:@"POST" paras:@{@"email":email} completion:^(NSData *data, NSError *error) { 173 [self _request:[kServerAddress stringByAppendingFormat: @"forgetPass"] method:@"POST" paras:@{@"email":email} completion:^(NSData *data, NSError *error) {
150 174
151 if (completion == NULL) { 175 if (completion == NULL) {
152 return ; 176 return ;
153 } 177 }
154 178
155 if (error == nil) 179 if (error == nil)
156 { 180 {
157 NSDictionary *dataResult = [NSJSONSerialization JSONObjectWithData:data options: NSJSONReadingAllowFragments error: &error]; 181 NSDictionary *dataResult = [NSJSONSerialization JSONObjectWithData:data options: NSJSONReadingAllowFragments error: &error];
158 182
159 int status = [dataResult[@"status"] intValue]; 183 int status = [dataResult[@"status"] intValue];
160 if (status == 1) { // status = 1 success 184 if (status == 1) { // status = 1 success
161 completion(nil); 185 completion(nil);
162 } 186 }
163 else { // status = 0 error 187 else { // status = 0 error
164 NSString *message = dataResult[@"message"]; 188 NSString *message = dataResult[@"message"];
165 NSError *forgetPass = [NSError errorWithDomain:@"LifeLog_Domain" code:-1 userInfo:@{@"message":message}]; 189 NSError *forgetPass = [NSError errorWithDomain:@"LifeLog_Domain" code:-1 userInfo:@{@"message":message}];
166 completion(forgetPass); 190 completion(forgetPass);
167 } 191 }
168 } 192 }
169 else 193 else
170 { 194 {
171 completion(error); 195 completion(error);
172 } 196 }
173 }]; 197 }];
174 } 198 }
175 - (void)confirmForgetPass:(NSString *)email withConfirm:(NSString *)confirm CompletionHandler:(void (^)(NSError *)) completion { 199 - (void)confirmForgetPass:(NSString *)email withConfirm:(NSString *)confirm CompletionHandler:(void (^)(NSError *)) completion {
176 [self _request:[kServerAddress stringByAppendingFormat: @"forgetPass/confirm"] method:@"POST" paras:@{@"email":email, @"code_confirm": confirm} completion:^(NSData *data, NSError *error) { 200 [self _request:[kServerAddress stringByAppendingFormat: @"forgetPass/confirm"] method:@"POST" paras:@{@"email":email, @"code_confirm": confirm} completion:^(NSData *data, NSError *error) {
177 201
178 if (completion == NULL) { 202 if (completion == NULL) {
179 return ; 203 return ;
180 } 204 }
181 205
182 if (error == nil) 206 if (error == nil)
183 { 207 {
184 NSDictionary *dataResult = [NSJSONSerialization JSONObjectWithData:data options: NSJSONReadingAllowFragments error: &error]; 208 NSDictionary *dataResult = [NSJSONSerialization JSONObjectWithData:data options: NSJSONReadingAllowFragments error: &error];
185 209
186 int status = [dataResult[@"status"] intValue]; 210 int status = [dataResult[@"status"] intValue];
187 if (status == 1) { // status = 1 success 211 if (status == 1) { // status = 1 success
188 completion(nil); 212 completion(nil);
189 } 213 }
190 else { // status = 0 error 214 else { // status = 0 error
191 NSString *message = dataResult[@"message"]; 215 NSString *message = dataResult[@"message"];
192 NSError *confirmForgetPass = [NSError errorWithDomain:@"LifeLog_Domain" code:-1 userInfo:@{@"message":message}]; 216 NSError *confirmForgetPass = [NSError errorWithDomain:@"LifeLog_Domain" code:-1 userInfo:@{@"message":message}];
193 completion(confirmForgetPass); 217 completion(confirmForgetPass);
194 } 218 }
195 } 219 }
196 else 220 else
197 { 221 {
198 completion(error); 222 completion(error);
199 } 223 }
200 }]; 224 }];
201 } 225 }
202 226
203 - (void)uploadImage:(NSString *)token andImageData:(NSData *)data CompletionHandler:(void (^)(NSString *, NSError *)) completion { 227 - (void)uploadImage:(NSString *)token andImageData:(NSData *)data CompletionHandler:(void (^)(NSString *, NSError *)) completion {
204 NSDictionary *dict = nil; 228 NSDictionary *dict = nil;
205 NSString *base64Encoded = [data base64EncodedStringWithOptions:0]; 229 NSString *base64Encoded = [data base64EncodedStringWithOptions:0];
206 if (token != nil) { 230 if (token != nil) {
207 dict = @{@"token":token, @"img": base64Encoded}; 231 dict = @{@"token":token, @"img": base64Encoded};
208 } 232 }
209 else { 233 else {
210 dict = @{@"img": base64Encoded}; 234 dict = @{@"img": base64Encoded};
211 } 235 }
212 [self _request:[kServerAddress stringByAppendingFormat: @"upload-image"] method:@"POST" paras:dict completion:^(NSData *data, NSError *error) { 236 [self _request:[kServerAddress stringByAppendingFormat: @"upload-image"] method:@"POST" paras:dict completion:^(NSData *data, NSError *error) {
213 237
214 if (completion == NULL) { 238 if (completion == NULL) {
215 return ; 239 return ;
216 } 240 }
217 241
218 if (error == nil) 242 if (error == nil)
219 { 243 {
220 NSDictionary *dataResult = [NSJSONSerialization JSONObjectWithData:data options: NSJSONReadingAllowFragments error: &error]; 244 NSDictionary *dataResult = [NSJSONSerialization JSONObjectWithData:data options: NSJSONReadingAllowFragments error: &error];
221 NSString *image_profile = [NSString stringWithFormat:@"%@", dataResult[@"message"]]; 245 NSString *image_profile = [NSString stringWithFormat:@"%@", dataResult[@"message"]];
222 completion(image_profile, nil); 246 completion(image_profile, nil);
223 } 247 }
224 else 248 else
225 { 249 {
226 completion(nil, error); 250 completion(nil, error);
227 } 251 }
228 }]; 252 }];
229 } 253 }
230 254
231 #pragma mark - Private Function 255 #pragma mark - Private Function
232 - (NSData *) _encodeDictionary: (NSDictionary *) dictionary 256 - (NSData *) _encodeDictionary: (NSDictionary *) dictionary
233 { 257 {
234 NSMutableArray *parts = [[NSMutableArray alloc] init]; 258 NSMutableArray *parts = [[NSMutableArray alloc] init];
235 for (id key in dictionary) 259 for (id key in dictionary)
236 { 260 {
237 NSString *encodedValue = [[dictionary[key] description] urlencode]; 261 NSString *encodedValue = [[dictionary[key] description] urlencode];
238 NSString *encodedKey = [[key description] urlencode];//[[key description] stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding]; 262 NSString *encodedKey = [[key description] urlencode];//[[key description] stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
239 NSString *part = [NSString stringWithFormat: @"%@=%@", encodedKey, encodedValue]; 263 NSString *part = [NSString stringWithFormat: @"%@=%@", encodedKey, encodedValue];
240 [parts addObject:part]; 264 [parts addObject:part];
241 } 265 }
242 NSString *encodedDictionary = [parts componentsJoinedByString:@"&"]; 266 NSString *encodedDictionary = [parts componentsJoinedByString:@"&"];
243 return [encodedDictionary dataUsingEncoding: NSUTF8StringEncoding]; 267 return [encodedDictionary dataUsingEncoding: NSUTF8StringEncoding];
244 } 268 }
245 269
246 - (void) _request:(NSString *)address method:(NSString *)method paras:(NSDictionary *)paras completion:(void (^)(NSData *data, NSError *error))completion 270 - (void) _request:(NSString *)address method:(NSString *)method paras:(NSDictionary *)paras completion:(void (^)(NSData *data, NSError *error))completion
247 { 271 {
248 NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL: [NSURL URLWithString:address]]; 272 NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL: [NSURL URLWithString:address]];
249 request.HTTPMethod = method; 273 request.HTTPMethod = method;
250 [request setValue: @"application/json" forHTTPHeaderField: @"Accept"]; 274 [request setValue: @"application/json" forHTTPHeaderField: @"Accept"];
251 [request setValue: @"application/json" forHTTPHeaderField: @"Content-Type"]; 275 [request setValue: @"application/json" forHTTPHeaderField: @"Content-Type"];
252 [request setTimeoutInterval:self.timeOutInterval]; 276 [request setTimeoutInterval:self.timeOutInterval];
253 277
254 if (paras != nil) 278 if (paras != nil)
255 { 279 {
256 NSData *encodedData = [self _encodeDictionary: paras]; 280 NSData *encodedData = [self _encodeDictionary: paras];
257 [request setValue: [NSString stringWithFormat: @"%lu", (unsigned long) encodedData.length] forHTTPHeaderField: @"Content-Length"]; 281 [request setValue: [NSString stringWithFormat: @"%lu", (unsigned long) encodedData.length] forHTTPHeaderField: @"Content-Length"];
258 [request setValue: @"application/x-www-form-urlencoded charset=utf-8" forHTTPHeaderField: @"Content-Type"]; 282 [request setValue: @"application/x-www-form-urlencoded charset=utf-8" forHTTPHeaderField: @"Content-Type"];
259 [request setHTTPBody: encodedData]; 283 [request setHTTPBody: encodedData];
260 } 284 }
261 285
262 NSURLSession *session = [NSURLSession sharedSession]; 286 NSURLSession *session = [NSURLSession sharedSession];
263 NSURLSessionDataTask *task = [session dataTaskWithRequest:request 287 NSURLSessionDataTask *task = [session dataTaskWithRequest:request
264 completionHandler: 288 completionHandler:
265 ^(NSData *data, NSURLResponse *response, NSError *error) { 289 ^(NSData *data, NSURLResponse *response, NSError *error) {
266 if (completion == NULL) { 290 if (completion == NULL) {
267 return ; 291 return ;
268 } 292 }
269 if (error == nil) 293 if (error == nil)
270 { 294 {
271 completion(data, nil); 295 completion(data, nil);
272 } 296 }
273 else 297 else
274 { 298 {
275 completion(nil, error); 299 completion(nil, error);
276 } 300 }
277 }]; 301 }];
278 302
279 [task resume]; 303 [task resume];
280 } 304 }
281 305
282 @end 306 @end
283 307
LifeLog/LifeLog/User.h
1 // 1 //
2 // User.h 2 // User.h
3 // LifeLog 3 // LifeLog
4 // 4 //
5 // Created by Nguyen Van Phong on 7/30/17. 5 // Created by Nguyen Van Phong on 7/30/17.
6 // Copyright © 2017 PhongNV. All rights reserved. 6 // Copyright © 2017 PhongNV. All rights reserved.
7 // 7 //
8 8
9 #import <Foundation/Foundation.h> 9 #import <Foundation/Foundation.h>
10 10
11 @interface User : NSObject 11 @interface User : NSObject
12 @property (nonatomic, strong) NSString *user_id; 12 @property (nonatomic, strong) NSString *user_id;
13 @property (nonatomic, strong) NSString *username; 13 @property (nonatomic, strong) NSString *username;
14 @property (nonatomic, strong) NSString *password; 14 @property (nonatomic, strong) NSString *password;
15 @property (nonatomic, strong) NSString *full_name; 15 @property (nonatomic, strong) NSString *full_name;
16 @property (nonatomic, strong) NSString *nickname; 16 @property (nonatomic, strong) NSString *nickname;
17 @property (nonatomic, strong) NSString *birthday; 17 @property (nonatomic, strong) NSString *birthday;
18 @property (nonatomic, assign) float height; 18 @property (nonatomic, assign) float height;
19 @property (nonatomic, assign) float weight; 19 @property (nonatomic, assign) float weight;
20 @property (nonatomic, assign) int gender; // 0 & 1 20 @property (nonatomic, assign) int gender; // 0 & 1
21 @property (nonatomic, strong) NSString *address; 21 @property (nonatomic, strong) NSString *address;
22 @property (nonatomic, strong) NSString *user_description; 22 @property (nonatomic, strong) NSString *user_description;
23 @property (nonatomic, strong) NSString *email; 23 @property (nonatomic, strong) NSString *email;
24 @property (nonatomic, strong) NSString *phone; 24 @property (nonatomic, strong) NSString *phone;
25 @property (nonatomic, strong) NSString *created_at;
26 @property (nonatomic, assign) int delete_flag;
27 @property (nonatomic, assign) int fat_rate;
28 @property (nonatomic, strong) NSString *physical_activity;
29 @property (nonatomic, strong) NSString *profile_image;
30 @property (nonatomic, assign) int profiles_share;
31 @property (nonatomic, assign) int remember_me;
32 @property (nonatomic, assign) int sound_notifications_share;
33 @property (nonatomic, assign) int spend_calo_in_day;
34 @property (nonatomic, assign) int target;
35 @property (nonatomic, strong) NSString *updated_at;
25 @end 36 @end
26 37
LifeLog/LifeLog/User.m
1 // 1 //
2 // User.m 2 // User.m
3 // LifeLog 3 // LifeLog
4 // 4 //
5 // Created by Nguyen Van Phong on 7/30/17. 5 // Created by Nguyen Van Phong on 7/30/17.
6 // Copyright © 2017 PhongNV. All rights reserved. 6 // Copyright © 2017 PhongNV. All rights reserved.
7 // 7 //
8 8
9 #import "User.h" 9 #import "User.h"
10 10
11 @implementation User 11 @implementation User
12 - (id)initWithCoder:(NSCoder *)decoder { 12 - (id)initWithCoder:(NSCoder *)decoder {
13 self = [super init]; 13 self = [super init];
14 if (!self) { 14 if (!self) {
15 return nil; 15 return nil;
16 } 16 }
17 17
18 self.user_id = [decoder decodeObjectForKey:@"user_id"]; 18 self.user_id = [decoder decodeObjectForKey:@"user_id"];
19 self.username = [decoder decodeObjectForKey:@"username"]; 19 self.username = [decoder decodeObjectForKey:@"username"];
20 self.password = [decoder decodeObjectForKey:@"password"]; 20 self.password = [decoder decodeObjectForKey:@"password"];
21 self.full_name = [decoder decodeObjectForKey:@"full_name"]; 21 self.full_name = [decoder decodeObjectForKey:@"full_name"];
22 self.nickname = [decoder decodeObjectForKey:@"nickname"]; 22 self.nickname = [decoder decodeObjectForKey:@"nickname"];
23 self.birthday = [decoder decodeObjectForKey:@"birthday"]; 23 self.birthday = [decoder decodeObjectForKey:@"birthday"];
24 self.height = [decoder decodeFloatForKey:@"height"]; 24 self.height = [decoder decodeFloatForKey:@"height"];
25 self.weight = [decoder decodeFloatForKey:@"weight"]; 25 self.weight = [decoder decodeFloatForKey:@"weight"];
26 self.gender = [decoder decodeIntForKey:@"gender"]; 26 self.gender = [decoder decodeIntForKey:@"gender"];
27 self.address = [decoder decodeObjectForKey:@"address"]; 27 self.address = [decoder decodeObjectForKey:@"address"];
28 self.user_description = [decoder decodeObjectForKey:@"user_description"]; 28 self.user_description = [decoder decodeObjectForKey:@"user_description"];
29 self.email = [decoder decodeObjectForKey:@"email"]; 29 self.email = [decoder decodeObjectForKey:@"email"];
30 self.phone = [decoder decodeObjectForKey:@"phone"]; 30 self.phone = [decoder decodeObjectForKey:@"phone"];
31 self.created_at = [decoder decodeObjectForKey:@"created_at"];
32 self.physical_activity = [decoder decodeObjectForKey:@"physical_activity"];
33 self.profile_image = [decoder decodeObjectForKey:@"profile_image"];
34 self.updated_at = [decoder decodeObjectForKey:@"updated_at"];
35 self.delete_flag = [decoder decodeIntForKey:@"delete_flag"];
36 self.fat_rate = [decoder decodeIntForKey:@"fat_rate"];
37 self.profiles_share = [decoder decodeIntForKey:@"profiles_share"];
38 self.remember_me = [decoder decodeIntForKey:@"remember_me"];
39 self.sound_notifications_share = [decoder decodeIntForKey:@"sound_notifications_share"];
40 self.spend_calo_in_day = [decoder decodeIntForKey:@"spend_calo_in_day"];
41 self.target = [decoder decodeIntForKey:@"target"];
31 42
32 return self; 43 return self;
33 } 44 }
34 45
35 - (void)encodeWithCoder:(NSCoder *)encoder { 46 - (void)encodeWithCoder:(NSCoder *)encoder {
36 [encoder encodeObject:self.user_id forKey:@"user_id"]; 47 [encoder encodeObject:self.user_id forKey:@"user_id"];
37 [encoder encodeObject:self.username forKey:@"username"]; 48 [encoder encodeObject:self.username forKey:@"username"];
38 [encoder encodeObject:self.password forKey:@"password"]; 49 [encoder encodeObject:self.password forKey:@"password"];
39 [encoder encodeObject:self.full_name forKey:@"full_name"]; 50 [encoder encodeObject:self.full_name forKey:@"full_name"];
40 [encoder encodeObject:self.nickname forKey:@"nickname"]; 51 [encoder encodeObject:self.nickname forKey:@"nickname"];
41 [encoder encodeObject:self.birthday forKey:@"birthday"]; 52 [encoder encodeObject:self.birthday forKey:@"birthday"];
42 [encoder encodeFloat:self.height forKey:@"height"]; 53 [encoder encodeFloat:self.height forKey:@"height"];
43 [encoder encodeFloat:self.weight forKey:@"weight"]; 54 [encoder encodeFloat:self.weight forKey:@"weight"];
44 [encoder encodeInt:self.gender forKey:@"gender"]; 55 [encoder encodeInt:self.gender forKey:@"gender"];
45 [encoder encodeObject:self.address forKey:@"address"]; 56 [encoder encodeObject:self.address forKey:@"address"];
46 [encoder encodeObject:self.user_description forKey:@"user_description"]; 57 [encoder encodeObject:self.user_description forKey:@"user_description"];
47 [encoder encodeObject:self.email forKey:@"email"]; 58 [encoder encodeObject:self.email forKey:@"email"];
48 [encoder encodeObject:self.phone forKey:@"phone"]; 59 [encoder encodeObject:self.phone forKey:@"phone"];
60 [encoder encodeObject:self.created_at forKey:@"created_at"];
61 [encoder encodeObject:self.physical_activity forKey:@"physical_activity"];
62 [encoder encodeObject:self.profile_image forKey:@"profile_image"];
63 [encoder encodeObject:self.updated_at forKey:@"updated_at"];
64 [encoder encodeInt:self.delete_flag forKey:@"delete_flag"];
65 [encoder encodeInt:self.fat_rate forKey:@"fat_rate"];
66 [encoder encodeInt:self.profiles_share forKey:@"profiles_share"];
67 [encoder encodeInt:self.remember_me forKey:@"remember_me"];
68 [encoder encodeInt:self.sound_notifications_share forKey:@"sound_notifications_share"];
69 [encoder encodeInt:self.spend_calo_in_day forKey:@"spend_calo_in_day"];
70 [encoder encodeInt:self.target forKey:@"target"];
49 } 71 }
50 @end 72 @end
51 73