Commit cedcb87d8a4e170d8cb99ebeea59e5b739d6a220
1 parent
2bab9a9ab1
Exists in
master
and in
1 other branch
update MAP screen and update api get new token, api create log step
Showing 6 changed files with 433 additions and 29 deletions Inline Diff
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 | #import "ServerAPI.h" |
17 | 17 | ||
18 | static NSInteger numberTotal = 10000; | 18 | static NSInteger numberTotal = 10000; |
19 | 19 | ||
20 | @interface HomeViewController () | 20 | @interface HomeViewController () |
21 | { | 21 | { |
22 | MBProgressHUD *progressHud; | 22 | MBProgressHUD *progressHud; |
23 | } | 23 | } |
24 | @property (nonatomic, weak) IBOutlet UILabel *lblTitle; | 24 | @property (nonatomic, weak) IBOutlet UILabel *lblTitle; |
25 | @property (nonatomic, weak) IBOutlet UIImageView *avatar; | 25 | @property (nonatomic, weak) IBOutlet UIImageView *avatar; |
26 | @property (nonatomic, weak) IBOutlet UILabel *lblDateCurrent; | 26 | @property (nonatomic, weak) IBOutlet UILabel *lblDateCurrent; |
27 | @property (nonatomic, weak) IBOutlet UILabel *lblValueStep; | 27 | @property (nonatomic, weak) IBOutlet UILabel *lblValueStep; |
28 | @property (nonatomic, weak) IBOutlet UILabel *lblUnitStep; | 28 | @property (nonatomic, weak) IBOutlet UILabel *lblUnitStep; |
29 | @property (nonatomic, weak) IBOutlet UILabel *lblValueStepOther; | 29 | @property (nonatomic, weak) IBOutlet UILabel *lblValueStepOther; |
30 | @property (nonatomic, weak) IBOutlet UILabel *lblPercent; | 30 | @property (nonatomic, weak) IBOutlet UILabel *lblPercent; |
31 | @property (nonatomic, weak) IBOutlet UILabel *lblNotice; | 31 | @property (nonatomic, weak) IBOutlet UILabel *lblNotice; |
32 | @property (weak, nonatomic) IBOutlet UISegmentedControl *segmentHome; | 32 | @property (weak, nonatomic) IBOutlet UISegmentedControl *segmentHome; |
33 | 33 | ||
34 | @property (nonatomic, strong) CMPedometer *pedometer; | 34 | @property (nonatomic, strong) CMPedometer *pedometer; |
35 | @property (nonatomic, strong) CMMotionActivityManager *motionActivityManager; | 35 | @property (nonatomic, strong) CMMotionActivityManager *motionActivityManager; |
36 | @property (nonatomic, strong) NSOperationQueue *operationQueue; | 36 | @property (nonatomic, strong) NSOperationQueue *operationQueue; |
37 | @property (nonatomic, strong) NSTimer *timer; | 37 | @property (nonatomic, strong) NSTimer *timer; |
38 | @property (nonatomic, assign) NSInteger bike; | 38 | @property (nonatomic, assign) NSInteger bike; |
39 | @property (nonatomic, assign) NSInteger walking; | 39 | @property (nonatomic, assign) NSInteger walking; |
40 | @property (nonatomic, assign) NSInteger running; | 40 | @property (nonatomic, assign) NSInteger running; |
41 | @property (nonatomic, strong) NSDate *dateCurrent; | 41 | @property (nonatomic, strong) NSDate *dateCurrent; |
42 | 42 | ||
43 | //@property (nonatomic, assign) BOOL isRequesting; | 43 | //@property (nonatomic, assign) BOOL isRequesting; |
44 | @property (nonatomic, assign) int totalRequest; | 44 | @property (nonatomic, assign) int totalRequest; |
45 | @property (nonatomic, assign) int countComplete; | 45 | @property (nonatomic, assign) int countComplete; |
46 | 46 | ||
47 | @end | 47 | @end |
48 | 48 | ||
49 | @implementation HomeViewController | 49 | @implementation HomeViewController |
50 | 50 | ||
51 | - (void)viewDidLoad { | 51 | - (void)viewDidLoad { |
52 | [super viewDidLoad]; | 52 | [super viewDidLoad]; |
53 | // Do any additional setup after loading the view from its nib. | 53 | // Do any additional setup after loading the view from its nib. |
54 | self.lblTitle.text = NSLocalizedString(@"lifelog.home.title", nil); | 54 | self.lblTitle.text = NSLocalizedString(@"lifelog.home.title", nil); |
55 | 55 | ||
56 | [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]]; |
57 | 57 | ||
58 | self.avatar.backgroundColor = [UIColor whiteColor]; | 58 | self.avatar.backgroundColor = [UIColor whiteColor]; |
59 | self.avatar.layer.borderWidth = 2.0f; | 59 | self.avatar.layer.borderWidth = 2.0f; |
60 | self.avatar.layer.borderColor = [[UIColor whiteColor] CGColor]; | 60 | self.avatar.layer.borderColor = [[UIColor whiteColor] CGColor]; |
61 | self.avatar.layer.cornerRadius = self.avatar.frame.size.width/2.0f; | 61 | self.avatar.layer.cornerRadius = self.avatar.frame.size.width/2.0f; |
62 | self.avatar.layer.masksToBounds = YES; | 62 | self.avatar.layer.masksToBounds = YES; |
63 | NSData *data = [[NSUserDefaults standardUserDefaults] objectForKey:kUser]; | 63 | NSData *data = [[NSUserDefaults standardUserDefaults] objectForKey:kUser]; |
64 | User *user = (User *)[NSKeyedUnarchiver unarchiveObjectWithData:data]; | 64 | User *user = (User *)[NSKeyedUnarchiver unarchiveObjectWithData:data]; |
65 | if (user != nil) { | 65 | if (user != nil) { |
66 | NSString *linkImage = [NSString stringWithFormat:@"%@%@", kServerAddress, user.profile_image]; | 66 | NSString *linkImage = [NSString stringWithFormat:@"%@%@", kServerAddress, user.profile_image]; |
67 | NSURL *urlImage = [NSURL URLWithString:linkImage]; | 67 | NSURL *urlImage = [NSURL URLWithString:linkImage]; |
68 | NSURLSessionConfiguration *sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration]; | 68 | NSURLSessionConfiguration *sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration]; |
69 | sessionConfig.timeoutIntervalForRequest = 30.0; | 69 | sessionConfig.timeoutIntervalForRequest = 30.0; |
70 | sessionConfig.timeoutIntervalForResource = 60.0; | 70 | sessionConfig.timeoutIntervalForResource = 60.0; |
71 | sessionConfig.HTTPMaximumConnectionsPerHost = 20; | 71 | sessionConfig.HTTPMaximumConnectionsPerHost = 20; |
72 | sessionConfig.allowsCellularAccess = YES; | 72 | sessionConfig.allowsCellularAccess = YES; |
73 | HomeViewController __weak *weakSelf = self; | 73 | HomeViewController __weak *weakSelf = self; |
74 | NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfig]; | 74 | NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfig]; |
75 | NSURLSessionDataTask *downloadPhotoTask = [session | 75 | NSURLSessionDataTask *downloadPhotoTask = [session |
76 | dataTaskWithURL:urlImage completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { | 76 | dataTaskWithURL:urlImage completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { |
77 | if (weakSelf == nil) | 77 | if (weakSelf == nil) |
78 | { | 78 | { |
79 | return; | 79 | return; |
80 | } | 80 | } |
81 | if (error == nil) { | 81 | if (error == nil) { |
82 | UIImage *image = [[UIImage alloc] initWithData:data]; | 82 | UIImage *image = [[UIImage alloc] initWithData:data]; |
83 | [[NSOperationQueue mainQueue] addOperationWithBlock:^{ | 83 | [[NSOperationQueue mainQueue] addOperationWithBlock:^{ |
84 | weakSelf.avatar.image = image; | 84 | weakSelf.avatar.image = image; |
85 | }]; | 85 | }]; |
86 | } | 86 | } |
87 | }]; | 87 | }]; |
88 | [downloadPhotoTask resume]; | 88 | [downloadPhotoTask resume]; |
89 | } | 89 | } |
90 | 90 | ||
91 | self.lblNotice.text = NSLocalizedString(@"lifelog.home.notice", nil); | 91 | self.lblNotice.text = NSLocalizedString(@"lifelog.home.notice", nil); |
92 | 92 | ||
93 | _dateCurrent = [NSDate date]; | 93 | _dateCurrent = [NSDate date]; |
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)]; | 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)]; |
95 | 95 | ||
96 | self.lblUnitStep.text = NSLocalizedString(@"lifelog.home.unit.step", nil); | 96 | self.lblUnitStep.text = NSLocalizedString(@"lifelog.home.unit.step", nil); |
97 | 97 | ||
98 | if ([CMPedometer isStepCountingAvailable]) { | 98 | if ([CMPedometer isStepCountingAvailable]) { |
99 | _pedometer = [[CMPedometer alloc] init]; | 99 | _pedometer = [[CMPedometer alloc] init]; |
100 | } | 100 | } |
101 | if ([CMMotionActivityManager isActivityAvailable]) { | 101 | if ([CMMotionActivityManager isActivityAvailable]) { |
102 | _motionActivityManager = [[CMMotionActivityManager alloc] init]; | 102 | _motionActivityManager = [[CMMotionActivityManager alloc] init]; |
103 | } | 103 | } |
104 | _operationQueue = [[NSOperationQueue alloc] init]; | 104 | _operationQueue = [[NSOperationQueue alloc] init]; |
105 | _bike = 0; | 105 | _bike = 0; |
106 | _walking = 0; | 106 | _walking = 0; |
107 | _running = 0; | 107 | _running = 0; |
108 | _segmentHome.selectedSegmentIndex = 1; | 108 | _segmentHome.selectedSegmentIndex = 1; |
109 | // _isRequesting = NO; | 109 | // _isRequesting = NO; |
110 | _totalRequest = 0; | 110 | _totalRequest = 0; |
111 | _countComplete = 0; | 111 | _countComplete = 0; |
112 | 112 | ||
113 | progressHud = [MBProgressHUD showHUDAddedTo:self.view animated:YES]; | 113 | progressHud = [MBProgressHUD showHUDAddedTo:self.view animated:YES]; |
114 | progressHud.mode = MBProgressHUDModeIndeterminate; | 114 | progressHud.mode = MBProgressHUDModeIndeterminate; |
115 | progressHud.detailsLabel.text = NSLocalizedString(@"lifelog.home.progressHud.title", nil); | 115 | progressHud.detailsLabel.text = NSLocalizedString(@"lifelog.home.progressHud.title", nil); |
116 | } | 116 | } |
117 | 117 | ||
118 | - (void)viewWillAppear:(BOOL)animated { | 118 | - (void)viewWillAppear:(BOOL)animated { |
119 | [super viewWillAppear:animated]; | 119 | [super viewWillAppear:animated]; |
120 | // _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]; |
121 | // [_timer fire]; | 121 | // [_timer fire]; |
122 | [self countStep]; | 122 | [self countStep]; |
123 | 123 | ||
124 | NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; | 124 | NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; |
125 | [dateFormatter setDateFormat:@"yyyy-MM-dd"]; | 125 | [dateFormatter setDateFormat:@"yyyy-MM-dd"]; |
126 | NSString *dateString = [dateFormatter stringFromDate:_dateCurrent]; | 126 | NSString *dateString = [dateFormatter stringFromDate:_dateCurrent]; |
127 | 127 | ||
128 | HomeViewController __weak *weakSelf = self; | 128 | HomeViewController __weak *weakSelf = self; |
129 | [[ServerAPI server] requestTopWithMode:(int)_segmentHome.selectedSegmentIndex andDate:dateString CompletionHandler:^(TopObject *topObject, NSError *error) { | 129 | [[ServerAPI server] requestTopWithMode:(int)_segmentHome.selectedSegmentIndex andDate:dateString CompletionHandler:^(TopObject *topObject, NSError *error) { |
130 | if(weakSelf == nil) { | 130 | if(weakSelf == nil) { |
131 | return ; | 131 | return ; |
132 | } | 132 | } |
133 | if (error == nil) { | 133 | if (error == nil) { |
134 | NSLog(@"TopObject: %@", topObject); | 134 | NSLog(@"TopObject: %@", topObject); |
135 | } | 135 | } |
136 | else { | 136 | else { |
137 | dispatch_async(dispatch_get_main_queue(), ^{ | 137 | dispatch_async(dispatch_get_main_queue(), ^{ |
138 | NSString *message = [error.userInfo objectForKey:@"message"]; | 138 | NSString *message = [error.userInfo objectForKey:@"message"]; |
139 | [Utilities showErrorMessage:message withViewController:weakSelf]; | 139 | [Utilities showErrorMessage:message withViewController:weakSelf]; |
140 | }); | 140 | }); |
141 | } | 141 | } |
142 | }]; | 142 | }]; |
143 | } | 143 | } |
144 | 144 | ||
145 | - (void)viewWillDisappear:(BOOL)animated { | 145 | - (void)viewWillDisappear:(BOOL)animated { |
146 | [super viewWillDisappear:animated]; | 146 | [super viewWillDisappear:animated]; |
147 | //[_timer invalidate]; | 147 | //[_timer invalidate]; |
148 | } | 148 | } |
149 | 149 | ||
150 | - (void)didReceiveMemoryWarning { | 150 | - (void)didReceiveMemoryWarning { |
151 | [super didReceiveMemoryWarning]; | 151 | [super didReceiveMemoryWarning]; |
152 | // Dispose of any resources that can be recreated. | 152 | // Dispose of any resources that can be recreated. |
153 | } | 153 | } |
154 | 154 | ||
155 | #pragma mark - IBAction | 155 | #pragma mark - IBAction |
156 | - (IBAction)menuButtonTouchUpInside:(id)sender | 156 | - (IBAction)menuButtonTouchUpInside:(id)sender |
157 | { | 157 | { |
158 | 158 | ||
159 | } | 159 | } |
160 | 160 | ||
161 | - (IBAction)todayButtonTouchUpInside:(id)sender | 161 | - (IBAction)todayButtonTouchUpInside:(id)sender |
162 | { | 162 | { |
163 | TodayViewController *todayVC = [[TodayViewController alloc] initWithNibName:@"TodayViewController" bundle:nil]; | 163 | TodayViewController *todayVC = [[TodayViewController alloc] initWithNibName:@"TodayViewController" bundle:nil]; |
164 | [self.navigationController pushViewController:todayVC animated:YES]; | 164 | [self.navigationController pushViewController:todayVC animated:YES]; |
165 | } | 165 | } |
166 | 166 | ||
167 | - (IBAction)leftButtonTouchUpInside:(id)sender | 167 | - (IBAction)leftButtonTouchUpInside:(id)sender |
168 | { | 168 | { |
169 | self.dateCurrent = [self.dateCurrent dateByAddingTimeInterval:-(24*60*60)]; | 169 | self.dateCurrent = [self.dateCurrent dateByAddingTimeInterval:-(24*60*60)]; |
170 | 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)]; | 170 | 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)]; |
171 | [self countStep]; | 171 | [self countStep]; |
172 | } | 172 | } |
173 | 173 | ||
174 | - (IBAction)rightButtonTouchUpInside:(id)sender | 174 | - (IBAction)rightButtonTouchUpInside:(id)sender |
175 | { | 175 | { |
176 | self.dateCurrent = [self.dateCurrent dateByAddingTimeInterval:24*60*60]; | 176 | self.dateCurrent = [self.dateCurrent dateByAddingTimeInterval:24*60*60]; |
177 | 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)]; | 177 | 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)]; |
178 | [self countStep]; | 178 | [self countStep]; |
179 | } | 179 | } |
180 | 180 | ||
181 | - (IBAction)segmentValueChange:(id)sender { | 181 | - (IBAction)segmentValueChange:(id)sender { |
182 | [self updateStepUI]; | 182 | [self updateStepUI]; |
183 | } | 183 | } |
184 | 184 | ||
185 | #pragma mark - Functions Private | 185 | #pragma mark - Functions Private |
186 | - (void)countStep | 186 | - (void)countStep |
187 | { | 187 | { |
188 | // if (self.isRequesting == YES) { | 188 | // if (self.isRequesting == YES) { |
189 | // return; | 189 | // return; |
190 | // } | 190 | // } |
191 | if ([CMMotionActivityManager isActivityAvailable]) { | 191 | if ([CMMotionActivityManager isActivityAvailable]) { |
192 | [progressHud showAnimated:YES]; | 192 | [progressHud showAnimated:YES]; |
193 | [progressHud setHidden:NO]; | 193 | [progressHud setHidden:NO]; |
194 | // self.isRequesting = YES; | 194 | // self.isRequesting = YES; |
195 | self.bike = 0; | 195 | self.bike = 0; |
196 | self.walking = 0; | 196 | self.walking = 0; |
197 | self.running = 0; | 197 | self.running = 0; |
198 | NSDate *startDate = [self.dateCurrent beginningAtMidnightOfDay]; | 198 | NSDate *startDate = [self.dateCurrent beginningAtMidnightOfDay]; |
199 | NSDate *endDate = [startDate dateByAddingTimeInterval:(24*60*60 - 1)]; | 199 | NSDate *endDate = [startDate dateByAddingTimeInterval:(24*60*60 - 1)]; |
200 | 200 | ||
201 | HomeViewController __weak *weakSelf = self; | 201 | HomeViewController __weak *weakSelf = self; |
202 | dispatch_queue_t myQueue = dispatch_queue_create("mobileworld.jp.lifelog", NULL); | 202 | dispatch_queue_t myQueue = dispatch_queue_create("mobileworld.jp.lifelog", NULL); |
203 | dispatch_async(myQueue, ^{ | 203 | dispatch_async(myQueue, ^{ |
204 | if (weakSelf == nil) { | 204 | if (weakSelf == nil) { |
205 | return ; | 205 | return ; |
206 | } | 206 | } |
207 | 207 | ||
208 | [weakSelf.motionActivityManager queryActivityStartingFromDate:startDate toDate:endDate toQueue:_operationQueue withHandler:^(NSArray<CMMotionActivity *> * _Nullable activities, NSError * _Nullable error) { | 208 | [weakSelf.motionActivityManager queryActivityStartingFromDate:startDate toDate:endDate toQueue:_operationQueue withHandler:^(NSArray<CMMotionActivity *> * _Nullable activities, NSError * _Nullable error) { |
209 | if (error || activities.count <= 0) { | 209 | if (error || activities.count <= 0) { |
210 | weakSelf.totalRequest = 0; | 210 | weakSelf.totalRequest = 0; |
211 | weakSelf.countComplete = 0; | 211 | weakSelf.countComplete = 0; |
212 | dispatch_async(dispatch_get_main_queue(), ^{ | 212 | dispatch_async(dispatch_get_main_queue(), ^{ |
213 | [weakSelf updateStepUI]; | 213 | [weakSelf updateStepUI]; |
214 | }); | 214 | }); |
215 | return ; | 215 | return ; |
216 | } | 216 | } |
217 | // set EndDate | 217 | // set EndDate |
218 | weakSelf.totalRequest = (int)activities.count; | 218 | weakSelf.totalRequest = (int)activities.count; |
219 | NSMutableArray *arrayActivities = [[NSMutableArray alloc] init]; | 219 | NSMutableArray *arrayActivities = [[NSMutableArray alloc] init]; |
220 | for (int i = 0; i < activities.count; i++) { | 220 | for (int i = 0; i < activities.count; i++) { |
221 | CMMotionActivity *activity = [activities objectAtIndex:i]; | 221 | CMMotionActivity *activity = [activities objectAtIndex:i]; |
222 | CMMotionActivityExtra *activityExtra = [[CMMotionActivityExtra alloc] init]; | 222 | CMMotionActivityExtra *activityExtra = [[CMMotionActivityExtra alloc] init]; |
223 | activityExtra.activity = activity; | 223 | activityExtra.activity = activity; |
224 | if (i == activities.count - 1) { | 224 | if (i == activities.count - 1) { |
225 | activityExtra.endDate = endDate; | 225 | activityExtra.endDate = endDate; |
226 | } | 226 | } |
227 | else { | 227 | else { |
228 | CMMotionActivity *activityNext = [activities objectAtIndex:i+1]; | 228 | CMMotionActivity *activityNext = [activities objectAtIndex:i+1]; |
229 | activityExtra.endDate = activityNext.startDate; | 229 | activityExtra.endDate = activityNext.startDate; |
230 | } | 230 | } |
231 | [arrayActivities addObject:activityExtra]; | 231 | [arrayActivities addObject:activityExtra]; |
232 | } | 232 | } |
233 | 233 | ||
234 | for (CMMotionActivityExtra *activityExtra in arrayActivities) { | 234 | for (CMMotionActivityExtra *activityExtra in arrayActivities) { |
235 | // NSLog(@"%@", activityExtra.activity.startDate); | 235 | // NSLog(@"%@", activityExtra.activity.startDate); |
236 | [weakSelf.pedometer queryPedometerDataFromDate:activityExtra.activity.startDate toDate:activityExtra.endDate withHandler:^(CMPedometerData * _Nullable pedometerData, NSError * _Nullable error) { | 236 | [weakSelf.pedometer queryPedometerDataFromDate:activityExtra.activity.startDate toDate:activityExtra.endDate withHandler:^(CMPedometerData * _Nullable pedometerData, NSError * _Nullable error) { |
237 | NSInteger numberStep = [pedometerData.numberOfSteps integerValue]; | 237 | NSInteger numberStep = [pedometerData.numberOfSteps integerValue]; |
238 | 238 | int mode = 1; | |
239 | if (activityExtra.activity.cycling) { | 239 | if (activityExtra.activity.cycling) { |
240 | // self.bike | 240 | // self.bike |
241 | weakSelf.bike += numberStep; | 241 | weakSelf.bike += numberStep; |
242 | //NSLog(@"Step cycling"); | 242 | //NSLog(@"Step cycling"); |
243 | mode = 3; | ||
243 | } | 244 | } |
244 | else if (activityExtra.activity.walking) { | 245 | else if (activityExtra.activity.walking) { |
245 | // self.walking | 246 | // self.walking |
246 | weakSelf.walking += numberStep; | 247 | weakSelf.walking += numberStep; |
247 | //NSLog(@"Step walking"); | 248 | //NSLog(@"Step walking"); |
249 | mode = 1; | ||
248 | } | 250 | } |
249 | else if (activityExtra.activity.running) { | 251 | else if (activityExtra.activity.running) { |
250 | weakSelf.running += numberStep; | 252 | weakSelf.running += numberStep; |
251 | //NSLog(@"Step running"); | 253 | //NSLog(@"Step running"); |
254 | mode = 2; | ||
252 | } | 255 | } |
253 | else { | 256 | else { |
254 | // unknown | 257 | // unknown |
255 | //NSLog(@"Step unknown"); | 258 | //NSLog(@"Step unknown"); |
256 | } | 259 | } |
257 | // NSLog(@"Number of step--> %ld", numberStep); | 260 | // NSLog(@"Number of step--> %ld", numberStep); |
258 | weakSelf.countComplete += 1; | 261 | weakSelf.countComplete += 1; |
262 | |||
263 | // save step to server | ||
264 | if (numberStep > 0) { | ||
265 | NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; | ||
266 | [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"]; | ||
267 | NSString *dateBegin = [dateFormatter stringFromDate:activityExtra.activity.startDate]; | ||
268 | NSString *dateEnd = [dateFormatter stringFromDate:activityExtra.endDate]; | ||
269 | [[ServerAPI server] requestCreateLog:mode withStep:(int)numberStep startDate:dateBegin endDate:dateEnd CompletionHandler:^(NSError *error) { | ||
270 | if (error) { | ||
271 | NSLog(@"Error: %@", error); | ||
272 | } | ||
273 | }]; | ||
274 | } | ||
259 | dispatch_async(dispatch_get_main_queue(), ^{ | 275 | dispatch_async(dispatch_get_main_queue(), ^{ |
260 | [weakSelf updateStepUI]; | 276 | [weakSelf updateStepUI]; |
261 | }); | 277 | }); |
262 | }]; | 278 | }]; |
263 | } | 279 | } |
264 | // NSLog(@"-----------------------------------------------------"); | 280 | // NSLog(@"-----------------------------------------------------"); |
265 | }]; | 281 | }]; |
266 | }); | 282 | }); |
267 | } | 283 | } |
268 | else { | 284 | else { |
269 | [progressHud setHidden:YES]; | 285 | [progressHud setHidden:YES]; |
270 | } | 286 | } |
271 | } | 287 | } |
272 | 288 | ||
273 | - (void)updateStepUI //:(NSInteger)numberStep | 289 | - (void)updateStepUI //:(NSInteger)numberStep |
274 | { | 290 | { |
275 | if (self.totalRequest == self.countComplete) { | 291 | if (self.totalRequest == self.countComplete) { |
276 | switch (self.segmentHome.selectedSegmentIndex) { | 292 | switch (self.segmentHome.selectedSegmentIndex) { |
277 | case 0: | 293 | case 0: |
278 | self.lblValueStep.text = [Utilities addCommaFromNumber:self.bike]; | 294 | self.lblValueStep.text = [Utilities addCommaFromNumber:self.bike]; |
279 | self.lblValueStepOther.text = [NSString stringWithFormat:@"%@ %ld", NSLocalizedString(@"lifelog.today.remaining.other", nil), numberTotal - self.bike]; | 295 | self.lblValueStepOther.text = [NSString stringWithFormat:@"%@ %ld", NSLocalizedString(@"lifelog.today.remaining.other", nil), numberTotal - self.bike]; |
280 | self.lblPercent.text = [NSString stringWithFormat:@"%@ %i%@", NSLocalizedString(@"lifelog.today.text.percent", nil), (int)(self.bike*100/numberTotal), NSLocalizedString(@"lifelog.today.percent", nil)]; | 296 | self.lblPercent.text = [NSString stringWithFormat:@"%@ %i%@", NSLocalizedString(@"lifelog.today.text.percent", nil), (int)(self.bike*100/numberTotal), NSLocalizedString(@"lifelog.today.percent", nil)]; |
281 | break; | 297 | break; |
282 | 298 | ||
283 | case 1: | 299 | case 1: |
284 | self.lblValueStep.text = [Utilities addCommaFromNumber:self.walking]; | 300 | self.lblValueStep.text = [Utilities addCommaFromNumber:self.walking]; |
285 | self.lblValueStepOther.text = [NSString stringWithFormat:@"%@ %ld", NSLocalizedString(@"lifelog.today.remaining.other", nil), numberTotal - self.walking]; | 301 | self.lblValueStepOther.text = [NSString stringWithFormat:@"%@ %ld", NSLocalizedString(@"lifelog.today.remaining.other", nil), numberTotal - self.walking]; |
286 | self.lblPercent.text = [NSString stringWithFormat:@"%@ %i%@", NSLocalizedString(@"lifelog.today.text.percent", nil), (int)(self.walking*100/numberTotal), NSLocalizedString(@"lifelog.today.percent", nil)]; | 302 | self.lblPercent.text = [NSString stringWithFormat:@"%@ %i%@", NSLocalizedString(@"lifelog.today.text.percent", nil), (int)(self.walking*100/numberTotal), NSLocalizedString(@"lifelog.today.percent", nil)]; |
287 | break; | 303 | break; |
288 | 304 | ||
289 | case 2: | 305 | case 2: |
290 | self.lblValueStep.text = [Utilities addCommaFromNumber:self.running]; | 306 | self.lblValueStep.text = [Utilities addCommaFromNumber:self.running]; |
291 | self.lblValueStepOther.text = [NSString stringWithFormat:@"%@ %ld", NSLocalizedString(@"lifelog.today.remaining.other", nil), numberTotal - self.running]; | 307 | self.lblValueStepOther.text = [NSString stringWithFormat:@"%@ %ld", NSLocalizedString(@"lifelog.today.remaining.other", nil), numberTotal - self.running]; |
292 | self.lblPercent.text = [NSString stringWithFormat:@"%@ %i%@", NSLocalizedString(@"lifelog.today.text.percent", nil), (int)(self.running*100/numberTotal), NSLocalizedString(@"lifelog.today.percent", nil)]; | 308 | self.lblPercent.text = [NSString stringWithFormat:@"%@ %i%@", NSLocalizedString(@"lifelog.today.text.percent", nil), (int)(self.running*100/numberTotal), NSLocalizedString(@"lifelog.today.percent", nil)]; |
293 | break; | 309 | break; |
294 | 310 | ||
295 | default: | 311 | default: |
296 | break; | 312 | break; |
297 | } | 313 | } |
298 | // NSLog(@"Walking: %ld || Running: %ld || Bike: %ld", self.walking, self.running, self.bike); | 314 | // NSLog(@"Walking: %ld || Running: %ld || Bike: %ld", self.walking, self.running, self.bike); |
299 | // self.isRequesting = NO; | 315 | // self.isRequesting = NO; |
300 | self.countComplete = 0; | 316 | self.countComplete = 0; |
301 | self.totalRequest = 0; | 317 | self.totalRequest = 0; |
302 | [progressHud setHidden:YES]; | 318 | [progressHud setHidden:YES]; |
303 | } | 319 | } |
304 | } | 320 | } |
305 | 321 | ||
306 | @end | 322 | @end |
307 | 323 |
LifeLog/LifeLog/Info.plist
1 | <?xml version="1.0" encoding="UTF-8"?> | 1 | <?xml version="1.0" encoding="UTF-8"?> |
2 | <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> | 2 | <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> |
3 | <plist version="1.0"> | 3 | <plist version="1.0"> |
4 | <dict> | 4 | <dict> |
5 | <key>CFBundleDevelopmentRegion</key> | 5 | <key>CFBundleDevelopmentRegion</key> |
6 | <string>en</string> | 6 | <string>en</string> |
7 | <key>CFBundleExecutable</key> | 7 | <key>CFBundleExecutable</key> |
8 | <string>$(EXECUTABLE_NAME)</string> | 8 | <string>$(EXECUTABLE_NAME)</string> |
9 | <key>CFBundleIdentifier</key> | 9 | <key>CFBundleIdentifier</key> |
10 | <string>$(PRODUCT_BUNDLE_IDENTIFIER)</string> | 10 | <string>$(PRODUCT_BUNDLE_IDENTIFIER)</string> |
11 | <key>CFBundleInfoDictionaryVersion</key> | 11 | <key>CFBundleInfoDictionaryVersion</key> |
12 | <string>6.0</string> | 12 | <string>6.0</string> |
13 | <key>CFBundleName</key> | 13 | <key>CFBundleName</key> |
14 | <string>$(PRODUCT_NAME)</string> | 14 | <string>$(PRODUCT_NAME)</string> |
15 | <key>CFBundlePackageType</key> | 15 | <key>CFBundlePackageType</key> |
16 | <string>APPL</string> | 16 | <string>APPL</string> |
17 | <key>CFBundleShortVersionString</key> | 17 | <key>CFBundleShortVersionString</key> |
18 | <string>1.0</string> | 18 | <string>1.0</string> |
19 | <key>CFBundleURLTypes</key> | 19 | <key>CFBundleURLTypes</key> |
20 | <array> | 20 | <array> |
21 | <dict/> | 21 | <dict/> |
22 | </array> | 22 | </array> |
23 | <key>CFBundleVersion</key> | 23 | <key>CFBundleVersion</key> |
24 | <string>1</string> | 24 | <string>1</string> |
25 | <key>LSApplicationQueriesSchemes</key> | 25 | <key>LSApplicationQueriesSchemes</key> |
26 | <array> | 26 | <array> |
27 | <string>line</string> | 27 | <string>line</string> |
28 | </array> | 28 | </array> |
29 | <key>LSRequiresIPhoneOS</key> | 29 | <key>LSRequiresIPhoneOS</key> |
30 | <true/> | 30 | <true/> |
31 | <key>NSAppTransportSecurity</key> | 31 | <key>NSAppTransportSecurity</key> |
32 | <dict> | 32 | <dict> |
33 | <key>NSAllowsArbitraryLoads</key> | 33 | <key>NSAllowsArbitraryLoads</key> |
34 | <true/> | 34 | <true/> |
35 | </dict> | 35 | </dict> |
36 | <key>NSCameraUsageDescription</key> | 36 | <key>NSCameraUsageDescription</key> |
37 | <string>to take photos and video</string> | 37 | <string>to take photos and video</string> |
38 | <key>NSMotionUsageDescription</key> | 38 | <key>NSMotionUsageDescription</key> |
39 | <string>$(PRODUCT_NAME) motion use</string> | 39 | <string>$(PRODUCT_NAME) motion use</string> |
40 | <key>NSPhotoLibraryUsageDescription</key> | 40 | <key>NSPhotoLibraryUsageDescription</key> |
41 | <string>to save photos and videos</string> | 41 | <string>to save photos and videos</string> |
42 | <key>UILaunchStoryboardName</key> | 42 | <key>UILaunchStoryboardName</key> |
43 | <string>LaunchScreen</string> | 43 | <string>LaunchScreen</string> |
44 | <key>UIRequiredDeviceCapabilities</key> | 44 | <key>UIRequiredDeviceCapabilities</key> |
45 | <array> | 45 | <array> |
46 | <string>armv7</string> | 46 | <string>armv7</string> |
47 | </array> | 47 | </array> |
48 | <key>UIStatusBarHidden</key> | 48 | <key>UIStatusBarHidden</key> |
49 | <true/> | 49 | <true/> |
50 | <key>UISupportedInterfaceOrientations</key> | 50 | <key>UISupportedInterfaceOrientations</key> |
51 | <array> | 51 | <array> |
52 | <string>UIInterfaceOrientationPortrait</string> | 52 | <string>UIInterfaceOrientationPortrait</string> |
53 | </array> | 53 | </array> |
54 | <key>UISupportedInterfaceOrientations~ipad</key> | 54 | <key>UISupportedInterfaceOrientations~ipad</key> |
55 | <array> | 55 | <array> |
56 | <string>UIInterfaceOrientationPortrait</string> | 56 | <string>UIInterfaceOrientationPortrait</string> |
57 | <string>UIInterfaceOrientationPortraitUpsideDown</string> | 57 | <string>UIInterfaceOrientationPortraitUpsideDown</string> |
58 | <string>UIInterfaceOrientationLandscapeLeft</string> | 58 | <string>UIInterfaceOrientationLandscapeLeft</string> |
59 | <string>UIInterfaceOrientationLandscapeRight</string> | 59 | <string>UIInterfaceOrientationLandscapeRight</string> |
60 | </array> | 60 | </array> |
61 | <key>UIViewControllerBasedStatusBarAppearance</key> | 61 | <key>UIViewControllerBasedStatusBarAppearance</key> |
62 | <false/> | 62 | <false/> |
63 | <key>NSLocationWhenInUseUsageDescription</key> | ||
64 | <string>This application requires location services to work</string> | ||
65 | <key>NSLocationAlwaysUsageDescription</key> | ||
66 | <string>This application requires location services to work</string> | ||
63 | </dict> | 67 | </dict> |
64 | </plist> | 68 | </plist> |
65 | 69 |
LifeLog/LifeLog/MapViewController.m
1 | // | 1 | // |
2 | // MapViewController.m | 2 | // MapViewController.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 "MapViewController.h" | 9 | #import "MapViewController.h" |
10 | #import <MapKit/MapKit.h> | ||
11 | #import<CoreLocation/CoreLocation.h> | ||
12 | #import <CoreMotion/CoreMotion.h> | ||
13 | #import "NSDate+helper.h" | ||
14 | #import "Utilities.h" | ||
10 | 15 | ||
11 | @interface MapViewController () | 16 | @interface MapViewController ()<CLLocationManagerDelegate, MKMapViewDelegate> |
17 | { | ||
18 | CLGeocoder *geocoder; | ||
19 | CLPlacemark *placemark; | ||
20 | CLLocation *previousLocation; | ||
21 | } | ||
22 | @property (weak, nonatomic) IBOutlet MKMapView *mapView; | ||
23 | @property (weak, nonatomic) IBOutlet UILabel *lblTime; | ||
24 | @property (weak, nonatomic) IBOutlet UISlider *slider; | ||
12 | 25 | ||
26 | @property (nonatomic, weak) IBOutlet UILabel *lblValueStep; | ||
27 | @property (nonatomic, weak) IBOutlet UILabel *lblUnitStep; | ||
28 | |||
29 | @property (strong, nonatomic) CLLocationManager *locationManager; | ||
30 | |||
31 | @property (nonatomic, strong) CMPedometer *pedometer; | ||
32 | @property (nonatomic, strong) CMMotionActivityManager *motionActivityManager; | ||
33 | @property (nonatomic, strong) NSOperationQueue *operationQueue; | ||
34 | @property (nonatomic, strong) NSTimer *timer; | ||
35 | @property (nonatomic) int countTime; | ||
36 | @property (nonatomic, assign) BOOL isRequesting; | ||
13 | @end | 37 | @end |
14 | 38 | ||
15 | @implementation MapViewController | 39 | @implementation MapViewController |
16 | 40 | ||
17 | - (void)viewDidLoad { | 41 | - (void)viewDidLoad { |
18 | [super viewDidLoad]; | 42 | [super viewDidLoad]; |
19 | // Do any additional setup after loading the view from its nib. | 43 | // Do any additional setup after loading the view from its nib. |
20 | self.title = NSLocalizedString(@"lifelog.tapbar.map", nil); | 44 | self.title = NSLocalizedString(@"lifelog.tapbar.map", nil); |
45 | [self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.topLayoutGuide attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:self.mapView attribute:NSLayoutAttributeTop multiplier:1 constant:0]]; | ||
46 | geocoder = [[CLGeocoder alloc] init]; | ||
47 | [self setupLocation]; | ||
48 | [self setupMapView]; | ||
49 | previousLocation = nil; | ||
50 | |||
51 | if ([CMPedometer isStepCountingAvailable]) { | ||
52 | _pedometer = [[CMPedometer alloc] init]; | ||
53 | } | ||
54 | if ([CMMotionActivityManager isActivityAvailable]) { | ||
55 | _motionActivityManager = [[CMMotionActivityManager alloc] init]; | ||
56 | } | ||
57 | self.isRequesting = NO; | ||
58 | _countTime = 0; | ||
59 | self.lblUnitStep.text = NSLocalizedString(@"lifelog.home.unit.step", nil); | ||
21 | } | 60 | } |
22 | 61 | ||
23 | - (void)didReceiveMemoryWarning { | 62 | - (void)didReceiveMemoryWarning { |
24 | [super didReceiveMemoryWarning]; | 63 | [super didReceiveMemoryWarning]; |
25 | // Dispose of any resources that can be recreated. | 64 | // Dispose of any resources that can be recreated. |
65 | } | ||
66 | |||
67 | - (void)viewWillAppear:(BOOL)animated { | ||
68 | [super viewWillAppear:animated]; | ||
69 | _timer = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(countStep) userInfo:nil repeats:YES]; | ||
70 | [_timer fire]; | ||
71 | } | ||
72 | |||
73 | - (void)viewWillDisappear:(BOOL)animated { | ||
74 | [super viewWillDisappear:animated]; | ||
75 | [_timer invalidate]; | ||
76 | } | ||
77 | |||
78 | #pragma mark - CLLocationManagerDelegate | ||
79 | -(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations { | ||
80 | |||
81 | CLLocation *newLocation = [locations lastObject]; | ||
82 | if (previousLocation == nil) { | ||
83 | [self addAnnotationsOnMap:newLocation]; | ||
84 | } | ||
85 | else { | ||
86 | CLLocationCoordinate2D area[2]; | ||
87 | area[0] = previousLocation.coordinate; | ||
88 | area[1] = newLocation.coordinate; | ||
89 | MKPolyline *polyLine = [MKPolyline polylineWithCoordinates:area count:2]; | ||
90 | [_mapView addOverlay:polyLine]; | ||
91 | } | ||
92 | |||
93 | previousLocation = newLocation; | ||
94 | } | ||
95 | |||
96 | - (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error | ||
97 | { | ||
98 | NSLog(@"Cannot find the location."); | ||
99 | } | ||
100 | |||
101 | #pragma mark - MKMapViewDelegate | ||
102 | - (MKOverlayRenderer *)mapView:(MKMapView *)mapView rendererForOverlay:(id <MKOverlay>)overlay | ||
103 | { | ||
104 | if ([overlay isKindOfClass:[MKPolyline class]]) { | ||
105 | MKPolylineRenderer *pr = [[MKPolylineRenderer alloc] initWithOverlay:overlay]; | ||
106 | pr.strokeColor = [UIColor redColor]; | ||
107 | pr.lineWidth = 5; | ||
108 | return pr; | ||
109 | } | ||
110 | return nil; | ||
111 | } | ||
112 | |||
113 | #pragma mark - Functions Private | ||
114 | |||
115 | - (void)addAnnotationsOnMap:(CLLocation *)locationToPoint { | ||
116 | MKPointAnnotation *annotation = [[MKPointAnnotation alloc] init]; | ||
117 | annotation.coordinate = locationToPoint.coordinate; | ||
118 | [geocoder reverseGeocodeLocation:locationToPoint completionHandler:^(NSArray *placemarks, NSError *error) { | ||
119 | if (error == nil && [placemarks count] >0) { | ||
120 | placemark = [placemarks firstObject]; | ||
121 | NSDictionary *addressDict = placemark.addressDictionary; | ||
122 | annotation.title = [NSString stringWithFormat:@"%@", addressDict[@"Name"]]; | ||
123 | [_mapView addAnnotation:annotation]; | ||
124 | } | ||
125 | }]; | ||
126 | } | ||
127 | |||
128 | - (void)setupLocation { | ||
129 | _locationManager = [[CLLocationManager alloc] init]; | ||
130 | _locationManager.desiredAccuracy = kCLLocationAccuracyBest; | ||
131 | _locationManager.delegate = self; | ||
132 | CLAuthorizationStatus status = [CLLocationManager authorizationStatus]; | ||
133 | if (status == kCLAuthorizationStatusNotDetermined || status == kCLAuthorizationStatusDenied || status == kCLAuthorizationStatusAuthorizedWhenInUse) { | ||
134 | [_locationManager requestWhenInUseAuthorization]; | ||
135 | [_locationManager requestAlwaysAuthorization]; | ||
136 | } | ||
137 | [_locationManager startUpdatingLocation]; | ||
138 | [_locationManager startUpdatingHeading]; | ||
139 | } | ||
140 | |||
141 | - (void)setupMapView { | ||
142 | _mapView.delegate = self; | ||
143 | _mapView.showsUserLocation = YES; | ||
144 | _mapView.mapType = MKMapTypeStandard; | ||
145 | _mapView.userTrackingMode = MKUserTrackingModeFollowWithHeading; | ||
146 | } | ||
147 | |||
148 | #pragma mark - Functions Private | ||
149 | - (void)countStep | ||
150 | { | ||
151 | _countTime++; | ||
152 | _lblTime.text = [self convertTime:_countTime]; | ||
153 | _slider.value = _countTime; | ||
154 | if (self.isRequesting == YES) { | ||
155 | return; | ||
156 | } | ||
157 | if ([CMMotionActivityManager isActivityAvailable]) { | ||
158 | self.isRequesting = YES; | ||
159 | NSDate *endDate = [NSDate date]; | ||
160 | NSDate *startDate = [endDate beginningAtMidnightOfDay]; | ||
161 | MapViewController __weak *weakSelf = self; | ||
162 | dispatch_queue_t myQueue = dispatch_queue_create("mobileworld.jp.lifelog", NULL); | ||
163 | dispatch_async(myQueue, ^{ | ||
164 | if (weakSelf == nil) { | ||
165 | return ; | ||
166 | } | ||
167 | [weakSelf.pedometer queryPedometerDataFromDate:startDate toDate:endDate withHandler:^(CMPedometerData * _Nullable pedometerData, NSError * _Nullable error) { | ||
168 | NSInteger numberStep = [pedometerData.numberOfSteps integerValue]; | ||
169 | dispatch_async(dispatch_get_main_queue(), ^{ | ||
170 | [weakSelf updateStepUI:numberStep]; | ||
171 | }); | ||
172 | }]; | ||
173 | }); | ||
174 | } | ||
175 | } | ||
176 | |||
177 | - (NSString *)convertTime:(int)time | ||
178 | { | ||
179 | NSString *result = @""; | ||
180 | int hour = time/3600; | ||
181 | int minute = time/60; | ||
182 | int second = time % 60; | ||
183 | result = [NSString stringWithFormat:@"%02d:%02d:%02d", hour, minute, second]; | ||
184 | return result; | ||
185 | } | ||
186 | |||
187 | - (void)updateStepUI:(NSInteger)numberStep | ||
188 | { | ||
189 | // NSLog(@"Number of step: %ld", numberStep); | ||
190 | self.isRequesting = NO; | ||
191 | self.lblValueStep.text = [Utilities addCommaFromNumber:numberStep]; | ||
26 | } | 192 | } |
27 | 193 | ||
28 | @end | 194 | @end |
29 | 195 |
LifeLog/LifeLog/MapViewController.xib
1 | <?xml version="1.0" encoding="UTF-8"?> | 1 | <?xml version="1.0" encoding="UTF-8"?> |
2 | <document type="com.apple.InterfaceBuilder3.CocoaTouch.XIB" version="3.0" toolsVersion="12121" systemVersion="16F73" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" colorMatched="YES"> | 2 | <document type="com.apple.InterfaceBuilder3.CocoaTouch.XIB" version="3.0" toolsVersion="12121" systemVersion="16G29" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" colorMatched="YES"> |
3 | <device id="retina4_7" orientation="portrait"> | 3 | <device id="retina4_7" orientation="portrait"> |
4 | <adaptation id="fullscreen"/> | 4 | <adaptation id="fullscreen"/> |
5 | </device> | 5 | </device> |
6 | <dependencies> | 6 | <dependencies> |
7 | <deployment identifier="iOS"/> | ||
8 | <plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="12089"/> | 7 | <plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="12089"/> |
9 | <capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/> | 8 | <capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/> |
10 | </dependencies> | 9 | </dependencies> |
11 | <objects> | 10 | <objects> |
12 | <placeholder placeholderIdentifier="IBFilesOwner" id="-1" userLabel="File's Owner" customClass="MapViewController"> | 11 | <placeholder placeholderIdentifier="IBFilesOwner" id="-1" userLabel="File's Owner" customClass="MapViewController"> |
13 | <connections> | 12 | <connections> |
13 | <outlet property="lblTime" destination="EMF-vR-v3k" id="nRs-ga-YjW"/> | ||
14 | <outlet property="lblUnitStep" destination="bSt-HN-qcq" id="opK-5F-PG8"/> | ||
15 | <outlet property="lblValueStep" destination="qLg-XF-Dyf" id="lvl-yi-U7d"/> | ||
16 | <outlet property="mapView" destination="GCl-mf-CD8" id="SpU-ML-EIf"/> | ||
17 | <outlet property="slider" destination="79Q-XB-cW2" id="NXm-rp-Ycy"/> | ||
14 | <outlet property="view" destination="i5M-Pr-FkT" id="sfx-zR-JGt"/> | 18 | <outlet property="view" destination="i5M-Pr-FkT" id="sfx-zR-JGt"/> |
15 | </connections> | 19 | </connections> |
16 | </placeholder> | 20 | </placeholder> |
17 | <placeholder placeholderIdentifier="IBFirstResponder" id="-2" customClass="UIResponder"/> | 21 | <placeholder placeholderIdentifier="IBFirstResponder" id="-2" customClass="UIResponder"/> |
18 | <view clearsContextBeforeDrawing="NO" contentMode="scaleToFill" id="i5M-Pr-FkT"> | 22 | <view clearsContextBeforeDrawing="NO" contentMode="scaleToFill" id="i5M-Pr-FkT"> |
19 | <rect key="frame" x="0.0" y="0.0" width="375" height="667"/> | 23 | <rect key="frame" x="0.0" y="0.0" width="375" height="667"/> |
20 | <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/> | 24 | <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/> |
21 | <color key="backgroundColor" red="1" green="1" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/> | 25 | <subviews> |
26 | <mapView clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="scaleToFill" mapType="standard" translatesAutoresizingMaskIntoConstraints="NO" id="GCl-mf-CD8"> | ||
27 | <rect key="frame" x="0.0" y="0.0" width="375" height="579"/> | ||
28 | <connections> | ||
29 | <outlet property="delegate" destination="-1" id="fjQ-MR-pO8"/> | ||
30 | </connections> | ||
31 | </mapView> | ||
32 | <label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="" textAlignment="right" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="qLg-XF-Dyf" userLabel="valueStep"> | ||
33 | <rect key="frame" x="20" y="531" width="275" height="40"/> | ||
34 | <constraints> | ||
35 | <constraint firstAttribute="height" constant="40" id="uDh-v6-rG3"/> | ||
36 | </constraints> | ||
37 | <fontDescription key="fontDescription" type="system" pointSize="45"/> | ||
38 | <color key="textColor" red="0.047200520830000002" green="1" blue="0.0" alpha="1" colorSpace="calibratedRGB"/> | ||
39 | <nil key="highlightedColor"/> | ||
40 | </label> | ||
41 | <label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="step" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="bSt-HN-qcq" userLabel="unitStep"> | ||
42 | <rect key="frame" x="305" y="541" width="50" height="30"/> | ||
43 | <constraints> | ||
44 | <constraint firstAttribute="height" constant="30" id="CNj-tm-yOG"/> | ||
45 | <constraint firstAttribute="width" constant="50" id="fac-mE-Hfh"/> | ||
46 | </constraints> | ||
47 | <fontDescription key="fontDescription" type="system" pointSize="25"/> | ||
48 | <color key="textColor" red="0.047200520830000002" green="1" blue="0.0" alpha="1" colorSpace="calibratedRGB"/> | ||
49 | <nil key="highlightedColor"/> | ||
50 | </label> | ||
51 | <view contentMode="scaleToFill" translatesAutoresizingMaskIntoConstraints="NO" id="ayh-Y4-2QM" userLabel="ViewOther"> | ||
52 | <rect key="frame" x="0.0" y="579" width="375" height="44"/> | ||
53 | <subviews> | ||
54 | <label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="TIME LINE" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="ibI-Db-Rc6"> | ||
55 | <rect key="frame" x="8" y="0.0" width="90" height="44"/> | ||
56 | <constraints> | ||
57 | <constraint firstAttribute="width" constant="90" id="Lof-Td-i7Y"/> | ||
58 | </constraints> | ||
59 | <fontDescription key="fontDescription" type="boldSystem" pointSize="17"/> | ||
60 | <nil key="textColor"/> | ||
61 | <nil key="highlightedColor"/> | ||
62 | </label> | ||
63 | <label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="12:05:01" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="EMF-vR-v3k"> | ||
64 | <rect key="frame" x="106" y="0.0" width="80" height="44"/> | ||
65 | <constraints> | ||
66 | <constraint firstAttribute="width" constant="80" id="57B-fF-bdc"/> | ||
67 | </constraints> | ||
68 | <fontDescription key="fontDescription" type="system" pointSize="17"/> | ||
69 | <nil key="textColor"/> | ||
70 | <nil key="highlightedColor"/> | ||
71 | </label> | ||
72 | <slider opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" minValue="0.0" maxValue="86400" translatesAutoresizingMaskIntoConstraints="NO" id="79Q-XB-cW2"> | ||
73 | <rect key="frame" x="192" y="7" width="177" height="31"/> | ||
74 | </slider> | ||
75 | </subviews> | ||
76 | <color key="backgroundColor" white="1" alpha="1" colorSpace="calibratedWhite"/> | ||
77 | <constraints> | ||
78 | <constraint firstItem="79Q-XB-cW2" firstAttribute="leading" secondItem="EMF-vR-v3k" secondAttribute="trailing" constant="8" id="0a0-t9-1tR"/> | ||
79 | <constraint firstItem="EMF-vR-v3k" firstAttribute="leading" secondItem="ibI-Db-Rc6" secondAttribute="trailing" constant="8" id="1a3-pA-ato"/> | ||
80 | <constraint firstAttribute="bottom" secondItem="79Q-XB-cW2" secondAttribute="bottom" constant="7" id="3l2-mK-se7"/> | ||
81 | <constraint firstItem="79Q-XB-cW2" firstAttribute="top" secondItem="ayh-Y4-2QM" secondAttribute="top" constant="7" id="6uV-xl-zpg"/> | ||
82 | <constraint firstAttribute="bottom" secondItem="EMF-vR-v3k" secondAttribute="bottom" id="7AD-qZ-VE4"/> | ||
83 | <constraint firstItem="EMF-vR-v3k" firstAttribute="top" secondItem="ayh-Y4-2QM" secondAttribute="top" id="B8d-wr-H0p"/> | ||
84 | <constraint firstAttribute="height" constant="44" id="G4K-Ic-5xS"/> | ||
85 | <constraint firstItem="ibI-Db-Rc6" firstAttribute="leading" secondItem="ayh-Y4-2QM" secondAttribute="leading" constant="8" id="NC8-xC-nBM"/> | ||
86 | <constraint firstAttribute="bottom" secondItem="ibI-Db-Rc6" secondAttribute="bottom" id="TKv-6Y-DHi"/> | ||
87 | <constraint firstAttribute="trailing" secondItem="79Q-XB-cW2" secondAttribute="trailing" constant="8" id="bzZ-US-1Hm"/> | ||
88 | <constraint firstItem="ibI-Db-Rc6" firstAttribute="top" secondItem="ayh-Y4-2QM" secondAttribute="top" id="lyI-MR-Y5S"/> | ||
89 | </constraints> | ||
90 | </view> | ||
91 | </subviews> | ||
92 | <color key="backgroundColor" white="0.0" alpha="1" colorSpace="calibratedWhite"/> | ||
93 | <constraints> | ||
94 | <constraint firstAttribute="bottom" secondItem="GCl-mf-CD8" secondAttribute="bottom" constant="88" id="8R5-IL-ZOZ"/> | ||
95 | <constraint firstItem="ayh-Y4-2QM" firstAttribute="top" secondItem="qLg-XF-Dyf" secondAttribute="bottom" constant="8" id="CCW-El-IlM"/> | ||
96 | <constraint firstAttribute="trailing" secondItem="bSt-HN-qcq" secondAttribute="trailing" constant="20" id="GmG-Qy-kpO"/> | ||
97 | <constraint firstAttribute="trailing" secondItem="ayh-Y4-2QM" secondAttribute="trailing" id="Mwo-O6-jk0"/> | ||
98 | <constraint firstAttribute="trailing" secondItem="GCl-mf-CD8" secondAttribute="trailing" id="PwQ-mm-AeM"/> | ||
99 | <constraint firstItem="GCl-mf-CD8" firstAttribute="top" secondItem="i5M-Pr-FkT" secondAttribute="top" placeholder="YES" id="TRc-4D-tbT"/> | ||
100 | <constraint firstItem="ayh-Y4-2QM" firstAttribute="leading" secondItem="i5M-Pr-FkT" secondAttribute="leading" id="Zc1-Ki-ENV"/> | ||
101 | <constraint firstItem="GCl-mf-CD8" firstAttribute="leading" secondItem="i5M-Pr-FkT" secondAttribute="leading" id="aM7-E7-p41"/> | ||
102 | <constraint firstItem="bSt-HN-qcq" firstAttribute="leading" secondItem="qLg-XF-Dyf" secondAttribute="trailing" constant="10" id="hlg-b5-9sd"/> | ||
103 | <constraint firstItem="qLg-XF-Dyf" firstAttribute="leading" secondItem="i5M-Pr-FkT" secondAttribute="leading" constant="20" id="nAo-mi-AuL"/> | ||
104 | <constraint firstItem="ayh-Y4-2QM" firstAttribute="top" secondItem="GCl-mf-CD8" secondAttribute="bottom" id="qaI-c1-69r"/> | ||
105 | <constraint firstItem="qLg-XF-Dyf" firstAttribute="centerY" secondItem="bSt-HN-qcq" secondAttribute="centerY" constant="-5" id="tA8-lE-abe"/> | ||
106 | </constraints> | ||
107 | <point key="canvasLocation" x="32.5" y="70.5"/> | ||
22 | </view> | 108 | </view> |
23 | </objects> | 109 | </objects> |
24 | </document> | 110 | </document> |
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 | 11 | ||
12 | extern NSString *const kServerAddress; | 12 | extern NSString *const kServerAddress; |
13 | extern NSString *const kUser; | 13 | extern NSString *const kUser; |
14 | extern NSString *const kToken; | 14 | extern NSString *const kToken; |
15 | extern NSString *const kNotificationToken; | 15 | extern NSString *const kNotificationToken; |
16 | 16 | ||
17 | @interface ServerAPI : NSObject | 17 | @interface ServerAPI : NSObject |
18 | + (instancetype) server; | 18 | + (instancetype) server; |
19 | @property (nonatomic, assign) NSTimeInterval timeOutInterval; | 19 | @property (nonatomic, assign) NSTimeInterval timeOutInterval; |
20 | 20 | ||
21 | #pragma mark - Login and Register | 21 | #pragma mark - Login and Register |
22 | - (void)loginWithEmail:(NSString *)email Password:(NSString *)password CompletionHandler: (void (^)(User *, NSString *, NSError *)) completion; | 22 | - (void)loginWithEmail:(NSString *)email Password:(NSString *)password CompletionHandler: (void (^)(User *, NSString *, NSError *)) completion; |
23 | - (void)registerUserWithParams:(NSDictionary *)params CompletionHandler: (void (^)(User *, NSString *, NSError *)) completion; | 23 | - (void)registerUserWithParams:(NSDictionary *)params CompletionHandler: (void (^)(User *, NSString *, NSError *)) completion; |
24 | - (void)uploadImage:(NSString *)token andImageData:(NSData *)data CompletionHandler:(void (^)(NSString *, NSError *)) completion; | 24 | - (void)uploadImage:(NSString *)token andImageData:(NSData *)data CompletionHandler:(void (^)(NSString *, NSError *)) completion; |
25 | - (void)forgetPass:(NSString *)email CompletionHandler:(void (^)(NSError *)) completion; | 25 | - (void)forgetPass:(NSString *)email CompletionHandler:(void (^)(NSError *)) completion; |
26 | - (void)confirmForgetPass:(NSString *)email withConfirm:(NSString *)confirm CompletionHandler:(void (^)(NSError *)) completion; | 26 | - (void)confirmForgetPass:(NSString *)email withConfirm:(NSString *)confirm CompletionHandler:(void (^)(NSError *)) completion; |
27 | 27 | ||
28 | #pragma mark - Home Screen Function | 28 | #pragma mark - Home Screen Function |
29 | - (void)requestTopWithMode:(int)mode andDate:(NSString *)date CompletionHandler:(void (^)(TopObject *, NSError *)) completion; | 29 | - (void)requestTopWithMode:(int)mode andDate:(NSString *)date CompletionHandler:(void (^)(TopObject *, NSError *)) completion; |
30 | - (void)requestCreateLog:(int)mode withStep:(int)numStep startDate:(NSString *)startDate endDate:(NSString *)endDate CompletionHandler:(void (^)(NSError *))completion; | ||
30 | 31 | ||
31 | #pragma mark - History Screen Function | 32 | #pragma mark - History Screen Function |
32 | - (void) requestHistory:(NSString *)token atDate:(NSDate *)date withType:(int)type andMode:(int) mode CompletionHandler:(void (^)(HistoryObject *, NSError *)) completion; | 33 | - (void) requestHistory:(NSString *)token atDate:(NSDate *)date withType:(int)type andMode:(int) mode CompletionHandler:(void (^)(HistoryObject *, NSError *)) completion; |
33 | - (void) requestHistoryGraph:(NSString *)token withType:(int)type andMode:(int) mode CompletionHandler:(void (^)(HistoryGraphObject *, NSError *)) completion; | 34 | - (void) requestHistoryGraph:(NSString *)token withType:(int)type andMode:(int) mode CompletionHandler:(void (^)(HistoryGraphObject *, NSError *)) completion; |
34 | - (void) requestHistoryList:(NSString *)token withType:(int)type andMode:(int) mode AtPage:(int) page CompletionHandler:(void (^)(NSArray *, NSError *)) completion; | 35 | - (void) requestHistoryList:(NSString *)token withType:(int)type andMode:(int) mode AtPage:(int) page CompletionHandler:(void (^)(NSArray *, NSError *)) completion; |
35 | 36 | ||
36 | #pragma mark - SNS Screen Function | 37 | #pragma mark - SNS Screen Function |
37 | /* | 38 | /* |
38 | Get tweet of group and get recent tweet is same API | 39 | Get tweet of group and get recent tweet is same API |
39 | If groupID equal -1, it will request recent tweet. Otherwise will request tweet of group | 40 | If groupID equal -1, it will request recent tweet. Otherwise will request tweet of group |
40 | */ | 41 | */ |
41 | - (void) requestTweetsList:(NSString *)token groupID: (int) groupID withPage:(int)page CompletionHandler:(void (^)(NSArray *, NSError *)) completion; | 42 | - (void) requestTweetsList:(NSString *)token groupID: (int) groupID withPage:(int)page CompletionHandler:(void (^)(NSArray *, NSError *)) completion; |
42 | - (void) searchGroup:(NSString *)token withKey:(NSString *)key andPage:(int)page CompletionHandler:(void (^)(NSArray *, NSError *)) completion; | 43 | - (void) searchGroup:(NSString *)token withKey:(NSString *)key andPage:(int)page CompletionHandler:(void (^)(NSArray *, NSError *)) completion; |
44 | #pragma mark - Common API | ||
45 | - (void)refreshToken: (NSString *)userID CompletionHandler:(void (^)(NSString *, NSError *))completion; | ||
43 | @end | 46 | @end |
44 | 47 |
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"; | 12 | NSString *const kUser = @"KEY_USER"; |
13 | NSString *const kToken = @"KEY_TOKEN"; | 13 | NSString *const kToken = @"KEY_TOKEN"; |
14 | NSString *const kNotificationToken = @"TOKEN_INVALID"; | 14 | NSString *const kNotificationToken = @"TOKEN_INVALID"; |
15 | 15 | ||
16 | @implementation NSString (NSString_Extended) | 16 | @implementation NSString (NSString_Extended) |
17 | - (NSString *)urlencode { | 17 | - (NSString *)urlencode { |
18 | NSMutableString *output = [NSMutableString string]; | 18 | NSMutableString *output = [NSMutableString string]; |
19 | const unsigned char *source = (const unsigned char *)[self UTF8String]; | 19 | const unsigned char *source = (const unsigned char *)[self UTF8String]; |
20 | int sourceLen = (int)strlen((const char *)source); | 20 | int sourceLen = (int)strlen((const char *)source); |
21 | for (int i = 0; i < sourceLen; ++i) { | 21 | for (int i = 0; i < sourceLen; ++i) { |
22 | const unsigned char thisChar = source[i]; | 22 | const unsigned char thisChar = source[i]; |
23 | if (thisChar == ' '){ | 23 | if (thisChar == ' '){ |
24 | [output appendString:@"+"]; | 24 | [output appendString:@"+"]; |
25 | } else if (thisChar == '.' || thisChar == '-' || thisChar == '_' || thisChar == '~' || | 25 | } else if (thisChar == '.' || thisChar == '-' || thisChar == '_' || thisChar == '~' || |
26 | (thisChar >= 'a' && thisChar <= 'z') || | 26 | (thisChar >= 'a' && thisChar <= 'z') || |
27 | (thisChar >= 'A' && thisChar <= 'Z') || | 27 | (thisChar >= 'A' && thisChar <= 'Z') || |
28 | (thisChar >= '0' && thisChar <= '9')) { | 28 | (thisChar >= '0' && thisChar <= '9')) { |
29 | [output appendFormat:@"%c", thisChar]; | 29 | [output appendFormat:@"%c", thisChar]; |
30 | } else { | 30 | } else { |
31 | [output appendFormat:@"%%%02X", thisChar]; | 31 | [output appendFormat:@"%%%02X", thisChar]; |
32 | } | 32 | } |
33 | } | 33 | } |
34 | return output; | 34 | return output; |
35 | } | 35 | } |
36 | @end | 36 | @end |
37 | 37 | ||
38 | @implementation ServerAPI | 38 | @implementation ServerAPI |
39 | static ServerAPI *_server = nil; | 39 | static ServerAPI *_server = nil; |
40 | 40 | ||
41 | NSURLSessionDataTask * searchTask; | 41 | NSURLSessionDataTask * searchTask; |
42 | 42 | ||
43 | @synthesize timeOutInterval = _timeOutInterval; | 43 | @synthesize timeOutInterval = _timeOutInterval; |
44 | 44 | ||
45 | + (instancetype)server | 45 | + (instancetype)server |
46 | { | 46 | { |
47 | @synchronized(self) { | 47 | @synchronized(self) { |
48 | if (_server == nil) { | 48 | if (_server == nil) { |
49 | _server = [[ServerAPI alloc] init]; | 49 | _server = [[ServerAPI alloc] init]; |
50 | } | 50 | } |
51 | } | 51 | } |
52 | return _server; | 52 | return _server; |
53 | } | 53 | } |
54 | 54 | ||
55 | - (instancetype)init | 55 | - (instancetype)init |
56 | { | 56 | { |
57 | self = [super init]; | 57 | self = [super init]; |
58 | if (self != nil) { | 58 | if (self != nil) { |
59 | self.timeOutInterval = 150; | 59 | self.timeOutInterval = 150; |
60 | } | 60 | } |
61 | return self; | 61 | return self; |
62 | } | 62 | } |
63 | 63 | ||
64 | #pragma mark - Login and Register | 64 | #pragma mark - Login and Register |
65 | // Login | 65 | // Login |
66 | - (void)loginWithEmail:(NSString *)email Password:(NSString *)password CompletionHandler: (void (^)(User *, NSString *, NSError *)) completion | 66 | - (void)loginWithEmail:(NSString *)email Password:(NSString *)password CompletionHandler: (void (^)(User *, NSString *, NSError *)) completion |
67 | { | 67 | { |
68 | [self _request:[kServerAddress stringByAppendingFormat: @"login"] method:@"POST" token:@"" paras:@{@"email":email, @"password": password} completion:^(NSData *data, NSError *error) { | 68 | [self _request:[kServerAddress stringByAppendingFormat: @"login"] method:@"POST" token:@"" paras:@{@"email":email, @"password": password} completion:^(NSData *data, NSError *error) { |
69 | 69 | ||
70 | if (completion == NULL) { | 70 | if (completion == NULL) { |
71 | return ; | 71 | return ; |
72 | } | 72 | } |
73 | 73 | ||
74 | if (error == nil) | 74 | if (error == nil) |
75 | { | 75 | { |
76 | NSDictionary *dataResult = [NSJSONSerialization JSONObjectWithData:data options: NSJSONReadingAllowFragments error: &error]; | 76 | NSDictionary *dataResult = [NSJSONSerialization JSONObjectWithData:data options: NSJSONReadingAllowFragments error: &error]; |
77 | 77 | ||
78 | int status = [dataResult[@"status"] intValue]; | 78 | int status = [dataResult[@"status"] intValue]; |
79 | if (status == 1) { // status = 1 success | 79 | if (status == 1) { // status = 1 success |
80 | NSString *token = dataResult[@"result"][@"token"]; | 80 | NSString *token = dataResult[@"result"][@"token"]; |
81 | NSDictionary *dictUser = dataResult[@"result"][@"user"]; | 81 | NSDictionary *dictUser = dataResult[@"result"][@"user"]; |
82 | User *user = [[User alloc] init]; | 82 | User *user = [[User alloc] init]; |
83 | user.user_id = [NSString stringWithFormat:@"%@",dictUser[@"id"]]; | 83 | user.user_id = [NSString stringWithFormat:@"%@",dictUser[@"id"]]; |
84 | user.username = [NSString stringWithFormat:@"%@",dictUser[@"username"]]; | 84 | user.username = [NSString stringWithFormat:@"%@",dictUser[@"username"]]; |
85 | user.full_name = [NSString stringWithFormat:@"%@",dictUser[@"full_name"]]; | 85 | user.full_name = [NSString stringWithFormat:@"%@",dictUser[@"full_name"]]; |
86 | user.nickname = [NSString stringWithFormat:@"%@",dictUser[@"nickname"]]; | 86 | user.nickname = [NSString stringWithFormat:@"%@",dictUser[@"nickname"]]; |
87 | user.email = [NSString stringWithFormat:@"%@",dictUser[@"email"]]; | 87 | user.email = [NSString stringWithFormat:@"%@",dictUser[@"email"]]; |
88 | user.password = [NSString stringWithFormat:@"%@",dictUser[@"password"]]; | 88 | user.password = [NSString stringWithFormat:@"%@",dictUser[@"password"]]; |
89 | user.birthday = [NSString stringWithFormat:@"%@",dictUser[@"birthday"]]; | 89 | user.birthday = [NSString stringWithFormat:@"%@",dictUser[@"birthday"]]; |
90 | user.address = [NSString stringWithFormat:@"%@",dictUser[@"address"]]; | 90 | user.address = [NSString stringWithFormat:@"%@",dictUser[@"address"]]; |
91 | user.gender = [[NSString stringWithFormat:@"%@",dictUser[@"gender"]] intValue]; | 91 | user.gender = [[NSString stringWithFormat:@"%@",dictUser[@"gender"]] intValue]; |
92 | user.height = [[NSString stringWithFormat:@"%@",dictUser[@"height"]] floatValue]; | 92 | user.height = [[NSString stringWithFormat:@"%@",dictUser[@"height"]] floatValue]; |
93 | user.weight = [[NSString stringWithFormat:@"%@",dictUser[@"weight"]] floatValue]; | 93 | user.weight = [[NSString stringWithFormat:@"%@",dictUser[@"weight"]] floatValue]; |
94 | user.user_description = [NSString stringWithFormat:@"%@",dictUser[@"description"]]; | 94 | user.user_description = [NSString stringWithFormat:@"%@",dictUser[@"description"]]; |
95 | user.created_at = [NSString stringWithFormat:@"%@",dictUser[@"created_at"]]; | 95 | user.created_at = [NSString stringWithFormat:@"%@",dictUser[@"created_at"]]; |
96 | user.physical_activity = [NSString stringWithFormat:@"%@",dictUser[@"physical_activity"]]; | 96 | user.physical_activity = [NSString stringWithFormat:@"%@",dictUser[@"physical_activity"]]; |
97 | user.profile_image = [NSString stringWithFormat:@"%@",dictUser[@"profile_image"]]; | 97 | user.profile_image = [NSString stringWithFormat:@"%@",dictUser[@"profile_image"]]; |
98 | user.updated_at = [NSString stringWithFormat:@"%@",dictUser[@"updated_at"]]; | 98 | user.updated_at = [NSString stringWithFormat:@"%@",dictUser[@"updated_at"]]; |
99 | user.delete_flag = [[NSString stringWithFormat:@"%@",dictUser[@"delete_flag"]] intValue]; | 99 | user.delete_flag = [[NSString stringWithFormat:@"%@",dictUser[@"delete_flag"]] intValue]; |
100 | user.fat_rate = [[NSString stringWithFormat:@"%@",dictUser[@"fat_rate"]] intValue]; | 100 | user.fat_rate = [[NSString stringWithFormat:@"%@",dictUser[@"fat_rate"]] intValue]; |
101 | user.profiles_share = [[NSString stringWithFormat:@"%@",dictUser[@"profiles_share"]] intValue]; | 101 | user.profiles_share = [[NSString stringWithFormat:@"%@",dictUser[@"profiles_share"]] intValue]; |
102 | user.remember_me = [[NSString stringWithFormat:@"%@",dictUser[@"remember_me"]] intValue]; | 102 | user.remember_me = [[NSString stringWithFormat:@"%@",dictUser[@"remember_me"]] intValue]; |
103 | user.sound_notifications_share = [[NSString stringWithFormat:@"%@",dictUser[@"sound_notifications_share"]] intValue]; | 103 | user.sound_notifications_share = [[NSString stringWithFormat:@"%@",dictUser[@"sound_notifications_share"]] intValue]; |
104 | user.spend_calo_in_day = [[NSString stringWithFormat:@"%@",dictUser[@"spend_calo_in_day"]] intValue]; | 104 | user.spend_calo_in_day = [[NSString stringWithFormat:@"%@",dictUser[@"spend_calo_in_day"]] intValue]; |
105 | user.target = [[NSString stringWithFormat:@"%@",dictUser[@"target"]] intValue]; | 105 | user.target = [[NSString stringWithFormat:@"%@",dictUser[@"target"]] intValue]; |
106 | completion(user, token, nil); | 106 | completion(user, token, nil); |
107 | } | 107 | } |
108 | else { // status = 0 error | 108 | else { // status = 0 error |
109 | NSString *message = dataResult[@"message"]; | 109 | NSString *message = dataResult[@"message"]; |
110 | if (message == nil) { | 110 | if (message == nil) { |
111 | message = @"Unknown error"; | 111 | message = @"Unknown error"; |
112 | } | 112 | } |
113 | NSError *loginFaild = [NSError errorWithDomain:@"LifeLog_Domain" code:-1 userInfo:@{@"message":message}]; | 113 | NSError *loginFaild = [NSError errorWithDomain:@"LifeLog_Domain" code:-1 userInfo:@{@"message":message}]; |
114 | completion(nil, nil, loginFaild); | 114 | completion(nil, nil, loginFaild); |
115 | } | 115 | } |
116 | } | 116 | } |
117 | else | 117 | else |
118 | { | 118 | { |
119 | completion(nil, nil, error); | 119 | completion(nil, nil, error); |
120 | } | 120 | } |
121 | }]; | 121 | }]; |
122 | } | 122 | } |
123 | 123 | ||
124 | // Register | 124 | // Register |
125 | - (void)registerUserWithParams:(NSDictionary *)params CompletionHandler: (void (^)(User *, NSString *, NSError *)) completion { | 125 | - (void)registerUserWithParams:(NSDictionary *)params CompletionHandler: (void (^)(User *, NSString *, NSError *)) completion { |
126 | [self _request:[kServerAddress stringByAppendingFormat: @"register"] method:@"POST" token:@"" paras:params completion:^(NSData *data, NSError *error) { | 126 | [self _request:[kServerAddress stringByAppendingFormat: @"register"] method:@"POST" token:@"" paras:params completion:^(NSData *data, NSError *error) { |
127 | 127 | ||
128 | if (completion == NULL) { | 128 | if (completion == NULL) { |
129 | return ; | 129 | return ; |
130 | } | 130 | } |
131 | 131 | ||
132 | if (error == nil) | 132 | if (error == nil) |
133 | { | 133 | { |
134 | NSDictionary *dataResult = [NSJSONSerialization JSONObjectWithData:data options: NSJSONReadingAllowFragments error: &error]; | 134 | NSDictionary *dataResult = [NSJSONSerialization JSONObjectWithData:data options: NSJSONReadingAllowFragments error: &error]; |
135 | 135 | ||
136 | int status = [dataResult[@"status"] intValue]; | 136 | int status = [dataResult[@"status"] intValue]; |
137 | if (status == 1) { // status = 1 success | 137 | if (status == 1) { // status = 1 success |
138 | NSString *token = dataResult[@"result"][@"token"]; | 138 | NSString *token = dataResult[@"result"][@"token"]; |
139 | NSDictionary *dictUser = dataResult[@"result"][@"user"]; | 139 | NSDictionary *dictUser = dataResult[@"result"][@"user"]; |
140 | User *user = [[User alloc] init]; | 140 | User *user = [[User alloc] init]; |
141 | user.user_id = [NSString stringWithFormat:@"%@",dictUser[@"id"]]; | 141 | user.user_id = [NSString stringWithFormat:@"%@",dictUser[@"id"]]; |
142 | user.username = [NSString stringWithFormat:@"%@",dictUser[@"username"]]; | 142 | user.username = [NSString stringWithFormat:@"%@",dictUser[@"username"]]; |
143 | user.full_name = [NSString stringWithFormat:@"%@",dictUser[@"full_name"]]; | 143 | user.full_name = [NSString stringWithFormat:@"%@",dictUser[@"full_name"]]; |
144 | user.nickname = [NSString stringWithFormat:@"%@",dictUser[@"nickname"]]; | 144 | user.nickname = [NSString stringWithFormat:@"%@",dictUser[@"nickname"]]; |
145 | user.email = [NSString stringWithFormat:@"%@",dictUser[@"email"]]; | 145 | user.email = [NSString stringWithFormat:@"%@",dictUser[@"email"]]; |
146 | user.password = [NSString stringWithFormat:@"%@",dictUser[@"password"]]; | 146 | user.password = [NSString stringWithFormat:@"%@",dictUser[@"password"]]; |
147 | user.birthday = [NSString stringWithFormat:@"%@",dictUser[@"birthday"]]; | 147 | user.birthday = [NSString stringWithFormat:@"%@",dictUser[@"birthday"]]; |
148 | user.address = [NSString stringWithFormat:@"%@",dictUser[@"address"]]; | 148 | user.address = [NSString stringWithFormat:@"%@",dictUser[@"address"]]; |
149 | user.gender = [[NSString stringWithFormat:@"%@",dictUser[@"gender"]] intValue]; | 149 | user.gender = [[NSString stringWithFormat:@"%@",dictUser[@"gender"]] intValue]; |
150 | user.height = [[NSString stringWithFormat:@"%@",dictUser[@"height"]] floatValue]; | 150 | user.height = [[NSString stringWithFormat:@"%@",dictUser[@"height"]] floatValue]; |
151 | user.weight = [[NSString stringWithFormat:@"%@",dictUser[@"weight"]] floatValue]; | 151 | user.weight = [[NSString stringWithFormat:@"%@",dictUser[@"weight"]] floatValue]; |
152 | user.user_description = [NSString stringWithFormat:@"%@",dictUser[@"description"]]; | 152 | user.user_description = [NSString stringWithFormat:@"%@",dictUser[@"description"]]; |
153 | user.created_at = [NSString stringWithFormat:@"%@",dictUser[@"created_at"]]; | 153 | user.created_at = [NSString stringWithFormat:@"%@",dictUser[@"created_at"]]; |
154 | user.physical_activity = [NSString stringWithFormat:@"%@",dictUser[@"physical_activity"]]; | 154 | user.physical_activity = [NSString stringWithFormat:@"%@",dictUser[@"physical_activity"]]; |
155 | user.profile_image = [NSString stringWithFormat:@"%@",dictUser[@"profile_image"]]; | 155 | user.profile_image = [NSString stringWithFormat:@"%@",dictUser[@"profile_image"]]; |
156 | user.updated_at = [NSString stringWithFormat:@"%@",dictUser[@"updated_at"]]; | 156 | user.updated_at = [NSString stringWithFormat:@"%@",dictUser[@"updated_at"]]; |
157 | user.delete_flag = [[NSString stringWithFormat:@"%@",dictUser[@"delete_flag"]] intValue]; | 157 | user.delete_flag = [[NSString stringWithFormat:@"%@",dictUser[@"delete_flag"]] intValue]; |
158 | user.fat_rate = [[NSString stringWithFormat:@"%@",dictUser[@"fat_rate"]] intValue]; | 158 | user.fat_rate = [[NSString stringWithFormat:@"%@",dictUser[@"fat_rate"]] intValue]; |
159 | user.profiles_share = [[NSString stringWithFormat:@"%@",dictUser[@"profiles_share"]] intValue]; | 159 | user.profiles_share = [[NSString stringWithFormat:@"%@",dictUser[@"profiles_share"]] intValue]; |
160 | user.remember_me = [[NSString stringWithFormat:@"%@",dictUser[@"remember_me"]] intValue]; | 160 | user.remember_me = [[NSString stringWithFormat:@"%@",dictUser[@"remember_me"]] intValue]; |
161 | user.sound_notifications_share = [[NSString stringWithFormat:@"%@",dictUser[@"sound_notifications_share"]] intValue]; | 161 | user.sound_notifications_share = [[NSString stringWithFormat:@"%@",dictUser[@"sound_notifications_share"]] intValue]; |
162 | user.spend_calo_in_day = [[NSString stringWithFormat:@"%@",dictUser[@"spend_calo_in_day"]] intValue]; | 162 | user.spend_calo_in_day = [[NSString stringWithFormat:@"%@",dictUser[@"spend_calo_in_day"]] intValue]; |
163 | user.target = [[NSString stringWithFormat:@"%@",dictUser[@"target"]] intValue]; | 163 | user.target = [[NSString stringWithFormat:@"%@",dictUser[@"target"]] intValue]; |
164 | completion(user, token, nil); | 164 | completion(user, token, nil); |
165 | } | 165 | } |
166 | else { // status = 0 error | 166 | else { // status = 0 error |
167 | NSString *message = dataResult[@"message"]; | 167 | NSString *message = dataResult[@"message"]; |
168 | if (message == nil) { | 168 | if (message == nil) { |
169 | message = @"Unknown error"; | 169 | message = @"Unknown error"; |
170 | } | 170 | } |
171 | NSError *loginFaild = [NSError errorWithDomain:@"LifeLog_Domain" code:-1 userInfo:@{@"message":message}]; | 171 | NSError *loginFaild = [NSError errorWithDomain:@"LifeLog_Domain" code:-1 userInfo:@{@"message":message}]; |
172 | completion(nil, nil, loginFaild); | 172 | completion(nil, nil, loginFaild); |
173 | } | 173 | } |
174 | } | 174 | } |
175 | else | 175 | else |
176 | { | 176 | { |
177 | completion(nil, nil, error); | 177 | completion(nil, nil, error); |
178 | } | 178 | } |
179 | }]; | 179 | }]; |
180 | } | 180 | } |
181 | 181 | ||
182 | - (void)forgetPass:(NSString *)email CompletionHandler:(void (^)(NSError *)) completion { | 182 | - (void)forgetPass:(NSString *)email CompletionHandler:(void (^)(NSError *)) completion { |
183 | [self _request:[kServerAddress stringByAppendingFormat: @"forgetPass"] method:@"POST" token:@"" paras:@{@"email":email} completion:^(NSData *data, NSError *error) { | 183 | [self _request:[kServerAddress stringByAppendingFormat: @"forgetPass"] method:@"POST" token:@"" paras:@{@"email":email} completion:^(NSData *data, NSError *error) { |
184 | 184 | ||
185 | if (completion == NULL) { | 185 | if (completion == NULL) { |
186 | return ; | 186 | return ; |
187 | } | 187 | } |
188 | 188 | ||
189 | if (error == nil) | 189 | if (error == nil) |
190 | { | 190 | { |
191 | NSDictionary *dataResult = [NSJSONSerialization JSONObjectWithData:data options: NSJSONReadingAllowFragments error: &error]; | 191 | NSDictionary *dataResult = [NSJSONSerialization JSONObjectWithData:data options: NSJSONReadingAllowFragments error: &error]; |
192 | 192 | ||
193 | int status = [dataResult[@"status"] intValue]; | 193 | int status = [dataResult[@"status"] intValue]; |
194 | if (status == 1) { // status = 1 success | 194 | if (status == 1) { // status = 1 success |
195 | completion(nil); | 195 | completion(nil); |
196 | } | 196 | } |
197 | else { // status = 0 error | 197 | else { // status = 0 error |
198 | NSString *message = dataResult[@"message"]; | 198 | NSString *message = dataResult[@"message"]; |
199 | if (message == nil) { | 199 | if (message == nil) { |
200 | message = @"Unknown error"; | 200 | message = @"Unknown error"; |
201 | } | 201 | } |
202 | NSError *forgetPass = [NSError errorWithDomain:@"LifeLog_Domain" code:-1 userInfo:@{@"message":message}]; | 202 | NSError *forgetPass = [NSError errorWithDomain:@"LifeLog_Domain" code:-1 userInfo:@{@"message":message}]; |
203 | completion(forgetPass); | 203 | completion(forgetPass); |
204 | } | 204 | } |
205 | } | 205 | } |
206 | else | 206 | else |
207 | { | 207 | { |
208 | completion(error); | 208 | completion(error); |
209 | } | 209 | } |
210 | }]; | 210 | }]; |
211 | } | 211 | } |
212 | - (void)confirmForgetPass:(NSString *)email withConfirm:(NSString *)confirm CompletionHandler:(void (^)(NSError *)) completion { | 212 | - (void)confirmForgetPass:(NSString *)email withConfirm:(NSString *)confirm CompletionHandler:(void (^)(NSError *)) completion { |
213 | [self _request:[kServerAddress stringByAppendingFormat: @"forgetPass/confirm"] method:@"POST" token:@"" paras:@{@"email":email, @"code_confirm": confirm} completion:^(NSData *data, NSError *error) { | 213 | [self _request:[kServerAddress stringByAppendingFormat: @"forgetPass/confirm"] method:@"POST" token:@"" paras:@{@"email":email, @"code_confirm": confirm} completion:^(NSData *data, NSError *error) { |
214 | 214 | ||
215 | if (completion == NULL) { | 215 | if (completion == NULL) { |
216 | return ; | 216 | return ; |
217 | } | 217 | } |
218 | 218 | ||
219 | if (error == nil) | 219 | if (error == nil) |
220 | { | 220 | { |
221 | NSDictionary *dataResult = [NSJSONSerialization JSONObjectWithData:data options: NSJSONReadingAllowFragments error: &error]; | 221 | NSDictionary *dataResult = [NSJSONSerialization JSONObjectWithData:data options: NSJSONReadingAllowFragments error: &error]; |
222 | 222 | ||
223 | int status = [dataResult[@"status"] intValue]; | 223 | int status = [dataResult[@"status"] intValue]; |
224 | if (status == 1) { // status = 1 success | 224 | if (status == 1) { // status = 1 success |
225 | completion(nil); | 225 | completion(nil); |
226 | } | 226 | } |
227 | else { // status = 0 error | 227 | else { // status = 0 error |
228 | NSString *message = dataResult[@"message"]; | 228 | NSString *message = dataResult[@"message"]; |
229 | NSError *confirmForgetPass = [NSError errorWithDomain:@"LifeLog_Domain" code:-1 userInfo:@{@"message":message}]; | 229 | NSError *confirmForgetPass = [NSError errorWithDomain:@"LifeLog_Domain" code:-1 userInfo:@{@"message":message}]; |
230 | completion(confirmForgetPass); | 230 | completion(confirmForgetPass); |
231 | } | 231 | } |
232 | } | 232 | } |
233 | else | 233 | else |
234 | { | 234 | { |
235 | completion(error); | 235 | completion(error); |
236 | } | 236 | } |
237 | }]; | 237 | }]; |
238 | } | 238 | } |
239 | 239 | ||
240 | - (void)uploadImage:(NSString *)token andImageData:(NSData *)data CompletionHandler:(void (^)(NSString *, NSError *)) completion { | 240 | - (void)uploadImage:(NSString *)token andImageData:(NSData *)data CompletionHandler:(void (^)(NSString *, NSError *)) completion { |
241 | NSDictionary *dict = nil; | 241 | NSDictionary *dict = nil; |
242 | NSString *base64Encoded = [data base64EncodedStringWithOptions:0]; | 242 | NSString *base64Encoded = [data base64EncodedStringWithOptions:0]; |
243 | if (token != nil) { | 243 | if (token != nil) { |
244 | dict = @{@"token":token, @"img": base64Encoded}; | 244 | dict = @{@"token":token, @"img": base64Encoded}; |
245 | } | 245 | } |
246 | else { | 246 | else { |
247 | dict = @{@"img": base64Encoded}; | 247 | dict = @{@"img": base64Encoded}; |
248 | } | 248 | } |
249 | [self _request:[kServerAddress stringByAppendingFormat: @"upload-image"] method:@"POST" token:token paras:dict completion:^(NSData *data, NSError *error) { | 249 | [self _request:[kServerAddress stringByAppendingFormat: @"upload-image"] method:@"POST" token:token paras:dict completion:^(NSData *data, NSError *error) { |
250 | 250 | ||
251 | if (completion == NULL) { | 251 | if (completion == NULL) { |
252 | return ; | 252 | return ; |
253 | } | 253 | } |
254 | 254 | ||
255 | if (error == nil) | 255 | if (error == nil) |
256 | { | 256 | { |
257 | NSDictionary *dataResult = [NSJSONSerialization JSONObjectWithData:data options: NSJSONReadingAllowFragments error: &error]; | 257 | NSDictionary *dataResult = [NSJSONSerialization JSONObjectWithData:data options: NSJSONReadingAllowFragments error: &error]; |
258 | NSString *image_profile = [NSString stringWithFormat:@"%@", dataResult[@"message"]]; | 258 | NSString *image_profile = [NSString stringWithFormat:@"%@", dataResult[@"message"]]; |
259 | completion(image_profile, nil); | 259 | completion(image_profile, nil); |
260 | } | 260 | } |
261 | else | 261 | else |
262 | { | 262 | { |
263 | completion(nil, error); | 263 | completion(nil, error); |
264 | } | 264 | } |
265 | }]; | 265 | }]; |
266 | } | 266 | } |
267 | 267 | ||
268 | -(NSString *) convertIntToString : (int) type { | 268 | -(NSString *) convertIntToString : (int) type { |
269 | switch (type) { | 269 | switch (type) { |
270 | case 1: | 270 | case 1: |
271 | return @"week"; | 271 | return @"week"; |
272 | break; | 272 | break; |
273 | case 2: | 273 | case 2: |
274 | return @"oneMonth"; | 274 | return @"oneMonth"; |
275 | break; | 275 | break; |
276 | case 3: | 276 | case 3: |
277 | return @"threeMonth"; | 277 | return @"threeMonth"; |
278 | break; | 278 | break; |
279 | case 4: | 279 | case 4: |
280 | return @"sixMonth"; | 280 | return @"sixMonth"; |
281 | break; | 281 | break; |
282 | default: | 282 | default: |
283 | return @"today"; | 283 | return @"today"; |
284 | break; | 284 | break; |
285 | } | 285 | } |
286 | } | 286 | } |
287 | 287 | ||
288 | #pragma mark - Home Screen Function | 288 | #pragma mark - Home Screen Function |
289 | - (void)requestTopWithMode:(int)mode andDate:(NSString *)date CompletionHandler:(void (^)(TopObject *, NSError *)) completion | 289 | - (void)requestTopWithMode:(int)mode andDate:(NSString *)date CompletionHandler:(void (^)(TopObject *, NSError *)) completion |
290 | { | 290 | { |
291 | NSString * token = [[NSUserDefaults standardUserDefaults] stringForKey:kToken]; | 291 | NSString * token = [[NSUserDefaults standardUserDefaults] stringForKey:kToken]; |
292 | NSString *url = [kServerAddress stringByAppendingFormat:@"/api/top/%d/%@", mode, date]; | 292 | NSString *url = [kServerAddress stringByAppendingFormat:@"api/top/%d/%@", mode, date]; |
293 | [self _request:url method:@"GET" token:token paras:nil completion:^(NSData *data, NSError *error) { | 293 | [self _request:url method:@"GET" token:token paras:nil completion:^(NSData *data, NSError *error) { |
294 | 294 | ||
295 | if (completion == NULL) { | 295 | if (completion == NULL) { |
296 | return ; | 296 | return ; |
297 | } | 297 | } |
298 | 298 | ||
299 | if (error == nil) | 299 | if (error == nil) |
300 | { | 300 | { |
301 | NSDictionary *dataResult = [NSJSONSerialization JSONObjectWithData:data options: NSJSONReadingAllowFragments error: &error]; | 301 | NSDictionary *dataResult = [NSJSONSerialization JSONObjectWithData:data options: NSJSONReadingAllowFragments error: &error]; |
302 | int status = [dataResult[@"status"] intValue]; | 302 | int status = [dataResult[@"status"] intValue]; |
303 | if (status == 1) { // status = 1 success | 303 | if (status == 1) { // status = 1 success |
304 | if(dataResult[@"result"] != nil) { | 304 | if(dataResult[@"result"] != nil) { |
305 | NSDictionary * dictResult = dataResult[@"result"]; | 305 | NSDictionary * dictResult = dataResult[@"result"]; |
306 | TopObject *topObject = [[TopObject alloc] init]; | 306 | TopObject *topObject = [[TopObject alloc] init]; |
307 | TargetInfor *targetInfor = [[TargetInfor alloc] initWithData:dictResult[@"targetInf"]]; | 307 | TargetInfor *targetInfor = [[TargetInfor alloc] initWithData:dictResult[@"targetInf"]]; |
308 | topObject.targetInfor = targetInfor; | 308 | topObject.targetInfor = targetInfor; |
309 | topObject.kcal = [[NSString stringWithFormat:@"%@", dictResult[@"kcal"]] intValue]; | 309 | topObject.kcal = [[NSString stringWithFormat:@"%@", dictResult[@"kcal"]] intValue]; |
310 | topObject.distance = [[NSString stringWithFormat:@"%@", dictResult[@"distance"]] floatValue]; | 310 | topObject.distance = [[NSString stringWithFormat:@"%@", dictResult[@"distance"]] floatValue]; |
311 | topObject.time = [NSString stringWithFormat:@"%@", dictResult[@"time"]]; | 311 | topObject.time = [NSString stringWithFormat:@"%@", dictResult[@"time"]]; |
312 | NSMutableArray *arrayStep = [[NSMutableArray alloc] init]; | 312 | NSMutableArray *arrayStep = [[NSMutableArray alloc] init]; |
313 | NSArray *array = dictResult[@"dataChart"]; | 313 | NSArray *array = dictResult[@"dataChart"]; |
314 | for(NSDictionary *dict in array) { | 314 | for(NSDictionary *dict in array) { |
315 | StepObject *object = [[StepObject alloc] init]; | 315 | StepObject *object = [[StepObject alloc] init]; |
316 | if([dict objectForKey:@"numStep"] != nil) { | 316 | if([dict objectForKey:@"numStep"] != nil) { |
317 | object.step = [dict[@"numStep"] intValue]; | 317 | object.step = [dict[@"numStep"] intValue]; |
318 | } | 318 | } |
319 | if([dict objectForKey:@"hour"] != nil) { | 319 | if([dict objectForKey:@"hour"] != nil) { |
320 | object.hour = [dict[@"hour"] intValue]; | 320 | object.hour = [dict[@"hour"] intValue]; |
321 | } | 321 | } |
322 | switch (mode) { | 322 | switch (mode) { |
323 | case 1: | 323 | case 1: |
324 | object.typeStep = @"walking"; | 324 | object.typeStep = @"walking"; |
325 | break; | 325 | break; |
326 | case 2: | 326 | case 2: |
327 | object.typeStep = @"running"; | 327 | object.typeStep = @"running"; |
328 | break; | 328 | break; |
329 | case 3: | 329 | case 3: |
330 | object.typeStep = @"bike"; | 330 | object.typeStep = @"bike"; |
331 | break; | 331 | break; |
332 | default: | 332 | default: |
333 | break; | 333 | break; |
334 | } | 334 | } |
335 | [arrayStep addObject:object]; | 335 | [arrayStep addObject:object]; |
336 | } | 336 | } |
337 | topObject.dataChart = [[NSMutableArray alloc] initWithArray:arrayStep]; | 337 | topObject.dataChart = [[NSMutableArray alloc] initWithArray:arrayStep]; |
338 | completion(topObject, nil); | 338 | completion(topObject, nil); |
339 | } | 339 | } |
340 | else { | 340 | else { |
341 | NSError *errorObject = [NSError errorWithDomain:@"LifeLog_Domain" code:-1 userInfo:@{@"message":@"Unknown Error"}]; | 341 | NSError *errorObject = [NSError errorWithDomain:@"LifeLog_Domain" code:-1 userInfo:@{@"message":@"Unknown Error"}]; |
342 | completion(nil, errorObject); | 342 | completion(nil, errorObject); |
343 | } | 343 | } |
344 | } | 344 | } |
345 | else { | 345 | else { |
346 | NSString *message = dataResult[@"message"]; | 346 | NSString *message = dataResult[@"message"]; |
347 | if (message == nil) { | 347 | if (message == nil) { |
348 | message = @"Unknown error"; | 348 | message = @"Unknown error"; |
349 | } | 349 | } |
350 | NSError *errorObject = [NSError errorWithDomain:@"LifeLog_Domain" code:-1 userInfo:@{@"message":message}]; | 350 | |
351 | completion(nil, errorObject); | 351 | if ([message isEqualToString:@"Token is invalid"]) { |
352 | [self checkToken:message]; | 352 | [self performSelectorOnMainThread:@selector(checkToken) withObject:nil waitUntilDone:YES]; |
353 | [self requestTopWithMode:mode andDate:date CompletionHandler:completion]; | ||
354 | } | ||
355 | else { | ||
356 | NSError *errorObject = [NSError errorWithDomain:@"LifeLog_Domain" code:-1 userInfo:@{@"message":message}]; | ||
357 | completion(nil, errorObject); | ||
358 | } | ||
353 | } | 359 | } |
354 | } | 360 | } |
355 | else | 361 | else |
356 | { | 362 | { |
357 | completion(nil, error); | 363 | completion(nil, error); |
358 | } | 364 | } |
359 | }]; | 365 | }]; |
360 | } | 366 | } |
361 | 367 | ||
368 | - (void)requestCreateLog:(int)mode withStep:(int)numStep startDate:(NSString *)startDate endDate:(NSString *)endDate CompletionHandler:(void (^)(NSError *))completion { | ||
369 | NSString * token = [[NSUserDefaults standardUserDefaults] stringForKey:kToken]; | ||
370 | NSString *url = [kServerAddress stringByAppendingFormat:@"api/createLog"]; | ||
371 | NSDictionary *dict = @{@"mode": [NSNumber numberWithInt:mode], @"numStep": [NSNumber numberWithInt:numStep], @"startTime": startDate, @"endTime": endDate}; | ||
372 | [self _request:url method:@"POST" token:token paras:dict completion:^(NSData *data, NSError *error) { | ||
373 | |||
374 | if (completion == NULL) { | ||
375 | return ; | ||
376 | } | ||
377 | |||
378 | if (error == nil) | ||
379 | { | ||
380 | NSDictionary *dataResult = [NSJSONSerialization JSONObjectWithData:data options: NSJSONReadingAllowFragments error: &error]; | ||
381 | int status = [dataResult[@"status"] intValue]; | ||
382 | if (status == 1) { // status = 1 success | ||
383 | completion(nil); | ||
384 | } | ||
385 | else { | ||
386 | NSString *message = dataResult[@"message"]; | ||
387 | if (message == nil) { | ||
388 | message = @"Unknown error"; | ||
389 | } | ||
390 | |||
391 | if ([message isEqualToString:@"Token is invalid"]) { | ||
392 | [self performSelectorOnMainThread:@selector(checkToken) withObject:nil waitUntilDone:YES]; | ||
393 | [self requestCreateLog:mode withStep:numStep startDate:startDate endDate:endDate CompletionHandler:completion]; | ||
394 | } | ||
395 | else { | ||
396 | NSError *errorObject = [NSError errorWithDomain:@"LifeLog_Domain" code:-1 userInfo:@{@"message":message}]; | ||
397 | completion(errorObject); | ||
398 | } | ||
399 | } | ||
400 | } | ||
401 | else | ||
402 | { | ||
403 | completion(error); | ||
404 | } | ||
405 | }]; | ||
406 | } | ||
407 | |||
362 | #pragma mark - History Screen Function | 408 | #pragma mark - History Screen Function |
363 | - (void) requestHistory:(NSString *)token atDate:(NSDate *)date withType:(int)type andMode:(int) mode CompletionHandler:(void (^)(HistoryObject *, NSError *)) completion { | 409 | - (void) requestHistory:(NSString *)token atDate:(NSDate *)date withType:(int)type andMode:(int) mode CompletionHandler:(void (^)(HistoryObject *, NSError *)) completion { |
364 | NSString *url = [kServerAddress stringByAppendingFormat:@"/api/history/%@/%d", [self convertIntToString:type], mode]; | 410 | NSString *url = [kServerAddress stringByAppendingFormat:@"/api/history/%@/%d", [self convertIntToString:type], mode]; |
365 | NSLog(@"requestHistory link %@", url); | 411 | NSLog(@"requestHistory link %@", url); |
366 | [self _request:url method:@"GET" token:token paras:nil completion:^(NSData *data, NSError *error) { | 412 | [self _request:url method:@"GET" token:token paras:nil completion:^(NSData *data, NSError *error) { |
367 | 413 | ||
368 | if (completion == NULL) { | 414 | if (completion == NULL) { |
369 | return ; | 415 | return ; |
370 | } | 416 | } |
371 | 417 | ||
372 | if (error == nil) | 418 | if (error == nil) |
373 | { | 419 | { |
374 | NSDictionary *dataResult = [NSJSONSerialization JSONObjectWithData:data options: NSJSONReadingAllowFragments error: &error]; | 420 | NSDictionary *dataResult = [NSJSONSerialization JSONObjectWithData:data options: NSJSONReadingAllowFragments error: &error]; |
375 | NSLog(@"%@", dataResult); | 421 | NSLog(@"%@", dataResult); |
376 | int status = [dataResult[@"status"] intValue]; | 422 | int status = [dataResult[@"status"] intValue]; |
377 | if (status == 1) { // status = 1 success | 423 | if (status == 1) { // status = 1 success |
378 | HistoryObject * object = [[HistoryObject alloc] initWithData:dataResult[@"result"]]; | 424 | HistoryObject * object = [[HistoryObject alloc] initWithData:dataResult[@"result"]]; |
379 | completion(object, nil); | 425 | completion(object, nil); |
380 | } | 426 | } |
381 | else { | 427 | else { |
382 | NSString *message = dataResult[@"message"]; | 428 | NSString *message = dataResult[@"message"]; |
383 | if (message == nil) { | 429 | if (message == nil) { |
384 | message = @"Unknown error"; | 430 | message = @"Unknown error"; |
385 | } | 431 | } |
386 | NSError *errorObject = [NSError errorWithDomain:@"LifeLog_Domain" code:-1 userInfo:@{@"message":message}]; | 432 | |
387 | completion(nil, errorObject); | 433 | if ([message isEqualToString:@"Token is invalid"]) { |
388 | [self checkToken:message]; | 434 | [self performSelectorOnMainThread:@selector(checkToken) withObject:nil waitUntilDone:YES]; |
435 | NSString *tokenNew = [[NSUserDefaults standardUserDefaults] objectForKey:kToken]; | ||
436 | [self requestHistory:tokenNew atDate:date withType:type andMode:mode CompletionHandler:completion]; | ||
437 | } | ||
438 | else { | ||
439 | NSError *errorObject = [NSError errorWithDomain:@"LifeLog_Domain" code:-1 userInfo:@{@"message":message}]; | ||
440 | completion(nil, errorObject); | ||
441 | } | ||
389 | } | 442 | } |
390 | } | 443 | } |
391 | else | 444 | else |
392 | { | 445 | { |
393 | completion(nil, error); | 446 | completion(nil, error); |
394 | } | 447 | } |
395 | }]; | 448 | }]; |
396 | } | 449 | } |
397 | 450 | ||
398 | - (void) requestHistoryGraph:(NSString *)token withType:(int)type andMode:(int) mode CompletionHandler:(void (^)(HistoryGraphObject *, NSError *)) completion { | 451 | - (void) requestHistoryGraph:(NSString *)token withType:(int)type andMode:(int) mode CompletionHandler:(void (^)(HistoryGraphObject *, NSError *)) completion { |
399 | NSString *url = [kServerAddress stringByAppendingFormat:@"/api/history/graph/%@/%d", [self convertIntToString:type], mode]; | 452 | NSString *url = [kServerAddress stringByAppendingFormat:@"/api/history/graph/%@/%d", [self convertIntToString:type], mode]; |
400 | NSLog(@"requestHistoryGraph link %@", url); | 453 | NSLog(@"requestHistoryGraph link %@", url); |
401 | [self _request:url method:@"GET" token:token paras:nil completion:^(NSData *data, NSError *error) { | 454 | [self _request:url method:@"GET" token:token paras:nil completion:^(NSData *data, NSError *error) { |
402 | 455 | ||
403 | if (completion == NULL) { | 456 | if (completion == NULL) { |
404 | return ; | 457 | return ; |
405 | } | 458 | } |
406 | 459 | ||
407 | if (error == nil) | 460 | if (error == nil) |
408 | { | 461 | { |
409 | NSDictionary *dataResult = [NSJSONSerialization JSONObjectWithData:data options: NSJSONReadingAllowFragments error: &error]; | 462 | NSDictionary *dataResult = [NSJSONSerialization JSONObjectWithData:data options: NSJSONReadingAllowFragments error: &error]; |
410 | NSLog(@"%@", dataResult); | 463 | NSLog(@"%@", dataResult); |
411 | int status = [dataResult[@"status"] intValue]; | 464 | int status = [dataResult[@"status"] intValue]; |
412 | if (status == 1) { // status = 1 success | 465 | if (status == 1) { // status = 1 success |
413 | HistoryGraphObject * object = [[HistoryGraphObject alloc] initWithData:dataResult[@"result"]]; | 466 | HistoryGraphObject * object = [[HistoryGraphObject alloc] initWithData:dataResult[@"result"]]; |
414 | completion(object, nil); | 467 | completion(object, nil); |
415 | } | 468 | } |
416 | else { | 469 | else { |
417 | NSString *message = dataResult[@"message"]; | 470 | NSString *message = dataResult[@"message"]; |
418 | if (message == nil) { | 471 | if (message == nil) { |
419 | message = @"Unknown error"; | 472 | message = @"Unknown error"; |
420 | } | 473 | } |
421 | NSError *errorObject = [NSError errorWithDomain:@"LifeLog_Domain" code:-1 userInfo:@{@"message":message}]; | 474 | |
422 | completion(nil, errorObject); | 475 | if ([message isEqualToString:@"Token is invalid"]) { |
423 | [self checkToken:message]; | 476 | [self performSelectorOnMainThread:@selector(checkToken) withObject:nil waitUntilDone:YES]; |
477 | NSString *tokenNew = [[NSUserDefaults standardUserDefaults] objectForKey:kToken]; | ||
478 | [self requestHistoryGraph:tokenNew withType:type andMode:mode CompletionHandler:completion]; | ||
479 | } | ||
480 | else { | ||
481 | NSError *errorObject = [NSError errorWithDomain:@"LifeLog_Domain" code:-1 userInfo:@{@"message":message}]; | ||
482 | completion(nil, errorObject); | ||
483 | } | ||
424 | } | 484 | } |
425 | } | 485 | } |
426 | else | 486 | else |
427 | { | 487 | { |
428 | completion(nil, error); | 488 | completion(nil, error); |
429 | } | 489 | } |
430 | }]; | 490 | }]; |
431 | } | 491 | } |
432 | 492 | ||
433 | - (void) requestHistoryList:(NSString *)token withType:(int)type andMode:(int) mode AtPage:(int) page CompletionHandler:(void (^)(NSArray *, NSError *)) completion { | 493 | - (void) requestHistoryList:(NSString *)token withType:(int)type andMode:(int) mode AtPage:(int) page CompletionHandler:(void (^)(NSArray *, NSError *)) completion { |
434 | NSString *url = [kServerAddress stringByAppendingFormat:@"/api/history/list/%@/%d?page=%d&record=50", [self convertIntToString:type], mode, page]; | 494 | NSString *url = [kServerAddress stringByAppendingFormat:@"/api/history/list/%@/%d?page=%d&record=50", [self convertIntToString:type], mode, page]; |
435 | NSLog(@"requestHistoryList link %@", url); | 495 | NSLog(@"requestHistoryList link %@", url); |
436 | [self _request:url method:@"GET" token:token paras:nil completion:^(NSData *data, NSError *error) { | 496 | [self _request:url method:@"GET" token:token paras:nil completion:^(NSData *data, NSError *error) { |
437 | 497 | ||
438 | if (completion == NULL) { | 498 | if (completion == NULL) { |
439 | return ; | 499 | return ; |
440 | } | 500 | } |
441 | 501 | ||
442 | if (error == nil) | 502 | if (error == nil) |
443 | { | 503 | { |
444 | NSDictionary *dataResult = [NSJSONSerialization JSONObjectWithData:data options: NSJSONReadingAllowFragments error: &error]; | 504 | NSDictionary *dataResult = [NSJSONSerialization JSONObjectWithData:data options: NSJSONReadingAllowFragments error: &error]; |
445 | NSLog(@"%@", dataResult); | 505 | NSLog(@"%@", dataResult); |
446 | int status = [dataResult[@"status"] intValue]; | 506 | int status = [dataResult[@"status"] intValue]; |
447 | if (status == 1) { // status = 1 success | 507 | if (status == 1) { // status = 1 success |
448 | if(dataResult[@"result"] != nil) { | 508 | if(dataResult[@"result"] != nil) { |
449 | NSArray * array = dataResult[@"result"][@"data"]; | 509 | NSArray * array = dataResult[@"result"][@"data"]; |
450 | NSMutableArray * arrayHistory = [[NSMutableArray alloc] init]; | 510 | NSMutableArray * arrayHistory = [[NSMutableArray alloc] init]; |
451 | for(NSDictionary * dict in array) { | 511 | for(NSDictionary * dict in array) { |
452 | HistoryObject * object = [[HistoryObject alloc] initWithData:dict]; | 512 | HistoryObject * object = [[HistoryObject alloc] initWithData:dict]; |
453 | [arrayHistory addObject:object]; | 513 | [arrayHistory addObject:object]; |
454 | } | 514 | } |
455 | completion(arrayHistory, nil); | 515 | completion(arrayHistory, nil); |
456 | } | 516 | } |
457 | else { | 517 | else { |
458 | NSError *errorObject = [NSError errorWithDomain:@"LifeLog_Domain" code:-1 userInfo:@{@"message":@"Unknown Error"}]; | 518 | NSError *errorObject = [NSError errorWithDomain:@"LifeLog_Domain" code:-1 userInfo:@{@"message":@"Unknown Error"}]; |
459 | completion(nil, errorObject); | 519 | completion(nil, errorObject); |
460 | } | 520 | } |
461 | } | 521 | } |
462 | else { | 522 | else { |
463 | NSString *message = dataResult[@"message"]; | 523 | NSString *message = dataResult[@"message"]; |
464 | if (message == nil) { | 524 | if (message == nil) { |
465 | message = @"Unknown error"; | 525 | message = @"Unknown error"; |
466 | } | 526 | } |
467 | NSError *errorObject = [NSError errorWithDomain:@"LifeLog_Domain" code:-1 userInfo:@{@"message":message}]; | 527 | |
468 | completion(nil, errorObject); | 528 | if ([message isEqualToString:@"Token is invalid"]) { |
469 | [self checkToken:message]; | 529 | [self performSelectorOnMainThread:@selector(checkToken) withObject:nil waitUntilDone:YES]; |
530 | NSString *tokenNew = [[NSUserDefaults standardUserDefaults] objectForKey:kToken]; | ||
531 | [self requestHistoryList:tokenNew withType:type andMode:mode AtPage:page CompletionHandler:completion]; | ||
532 | } | ||
533 | else { | ||
534 | NSError *errorObject = [NSError errorWithDomain:@"LifeLog_Domain" code:-1 userInfo:@{@"message":message}]; | ||
535 | completion(nil, errorObject); | ||
536 | } | ||
470 | } | 537 | } |
471 | } | 538 | } |
472 | else | 539 | else |
473 | { | 540 | { |
474 | completion(nil, error); | 541 | completion(nil, error); |
475 | } | 542 | } |
476 | }]; | 543 | }]; |
477 | } | 544 | } |
478 | 545 | ||
479 | #pragma mark - SNS Screen Function | 546 | #pragma mark - SNS Screen Function |
480 | - (void) requestTweetsList:(NSString *)token groupID: (int) groupID withPage:(int)page CompletionHandler:(void (^)(NSArray *, NSError *)) completion { | 547 | - (void) requestTweetsList:(NSString *)token groupID: (int) groupID withPage:(int)page CompletionHandler:(void (^)(NSArray *, NSError *)) completion { |
481 | NSString *url = [kServerAddress stringByAppendingFormat:@"/api/sns/%d", page]; | 548 | NSString *url = [kServerAddress stringByAppendingFormat:@"/api/sns/%d", page]; |
482 | if(groupID > -1) { | 549 | if(groupID > -1) { |
483 | url = [kServerAddress stringByAppendingFormat:@"api/tweet/list?group_id=%d&page=%d&record=10", groupID, page]; | 550 | url = [kServerAddress stringByAppendingFormat:@"api/tweet/list?group_id=%d&page=%d&record=10", groupID, page]; |
484 | } | 551 | } |
485 | NSLog(@"requestTweetsList link %@", url); | 552 | NSLog(@"requestTweetsList link %@", url); |
486 | [self _request:url method:@"GET" token:token paras:nil completion:^(NSData *data, NSError *error) { | 553 | [self _request:url method:@"GET" token:token paras:nil completion:^(NSData *data, NSError *error) { |
487 | 554 | ||
488 | if (completion == NULL) { | 555 | if (completion == NULL) { |
489 | return ; | 556 | return ; |
490 | } | 557 | } |
491 | 558 | ||
492 | if (error == nil) | 559 | if (error == nil) |
493 | { | 560 | { |
494 | NSDictionary *dataResult = [NSJSONSerialization JSONObjectWithData:data options: NSJSONReadingAllowFragments error: &error]; | 561 | NSDictionary *dataResult = [NSJSONSerialization JSONObjectWithData:data options: NSJSONReadingAllowFragments error: &error]; |
495 | NSLog(@"%@", dataResult); | 562 | NSLog(@"%@", dataResult); |
496 | int status = [dataResult[@"status"] intValue]; | 563 | int status = [dataResult[@"status"] intValue]; |
497 | if (status == 1) { // status = 1 success | 564 | if (status == 1) { // status = 1 success |
498 | if(dataResult[@"result"] != nil) { | 565 | if(dataResult[@"result"] != nil) { |
499 | NSArray * array = dataResult[@"result"]; | 566 | NSArray * array = dataResult[@"result"]; |
500 | NSMutableArray * arrayTweets = [[NSMutableArray alloc] init]; | 567 | NSMutableArray * arrayTweets = [[NSMutableArray alloc] init]; |
501 | for(NSDictionary * dict in array) { | 568 | for(NSDictionary * dict in array) { |
502 | TweetObject * object = [[TweetObject alloc] initWithData:dict]; | 569 | TweetObject * object = [[TweetObject alloc] initWithData:dict]; |
503 | [arrayTweets addObject:object]; | 570 | [arrayTweets addObject:object]; |
504 | } | 571 | } |
505 | completion(arrayTweets, nil); | 572 | completion(arrayTweets, nil); |
506 | } | 573 | } |
507 | else { | 574 | else { |
508 | NSError *errorObject = [NSError errorWithDomain:@"LifeLog_Domain" code:-1 userInfo:@{@"message":@"Unknown Error"}]; | 575 | NSError *errorObject = [NSError errorWithDomain:@"LifeLog_Domain" code:-1 userInfo:@{@"message":@"Unknown Error"}]; |
509 | completion(nil, errorObject); | 576 | completion(nil, errorObject); |
510 | } | 577 | } |
511 | } | 578 | } |
512 | else { | 579 | else { |
513 | NSString *message = dataResult[@"message"]; | 580 | NSString *message = dataResult[@"message"]; |
514 | NSError *errorObject = [NSError errorWithDomain:@"LifeLog_Domain" code:-1 userInfo:@{@"message":message}]; | 581 | if (message == nil) { |
515 | completion(nil, errorObject); | 582 | message = @"Unknown error"; |
516 | [self checkToken:message]; | 583 | } |
584 | |||
585 | if ([message isEqualToString:@"Token is invalid"]) { | ||
586 | [self performSelectorOnMainThread:@selector(checkToken) withObject:nil waitUntilDone:YES]; | ||
587 | NSString *tokenNew = [[NSUserDefaults standardUserDefaults] objectForKey:kToken]; | ||
588 | [self requestTweetsList:tokenNew groupID:groupID withPage:page CompletionHandler:completion]; | ||
589 | } | ||
590 | else { | ||
591 | NSError *errorObject = [NSError errorWithDomain:@"LifeLog_Domain" code:-1 userInfo:@{@"message":message}]; | ||
592 | completion(nil, errorObject); | ||
593 | } | ||
517 | } | 594 | } |
518 | } | 595 | } |
519 | else | 596 | else |
520 | { | 597 | { |
521 | completion(nil, error); | 598 | completion(nil, error); |
522 | } | 599 | } |
523 | }]; | 600 | }]; |
524 | } | 601 | } |
525 | 602 | ||
526 | - (void) searchGroup:(NSString *)token withKey:(NSString *)key andPage:(int)page CompletionHandler:(void (^)(NSArray *, NSError *)) completion { | 603 | - (void) searchGroup:(NSString *)token withKey:(NSString *)key andPage:(int)page CompletionHandler:(void (^)(NSArray *, NSError *)) completion { |
527 | NSString *url = [kServerAddress stringByAppendingFormat:@"api/sns/group/search"]; | 604 | NSString *url = [kServerAddress stringByAppendingFormat:@"api/sns/group/search"]; |
528 | NSLog(@"searchGroup link %@ page %d", url, page); | 605 | NSLog(@"searchGroup link %@ page %d", url, page); |
529 | if(searchTask != nil) { | 606 | if(searchTask != nil) { |
530 | [searchTask cancel]; | 607 | [searchTask cancel]; |
531 | } | 608 | } |
532 | 609 | ||
533 | searchTask = [self _request:url method:@"POST" token:token paras:@{@"keyword":key, @"page": [NSNumber numberWithInt:page]} completion:^(NSData *data, NSError *error) { | 610 | searchTask = [self _request:url method:@"POST" token:token paras:@{@"keyword":key, @"page": [NSNumber numberWithInt:page]} completion:^(NSData *data, NSError *error) { |
534 | searchTask = nil; | 611 | searchTask = nil; |
535 | if (completion == NULL) { | 612 | if (completion == NULL) { |
536 | return ; | 613 | return ; |
537 | } | 614 | } |
538 | 615 | ||
539 | if (error == nil) | 616 | if (error == nil) |
540 | { | 617 | { |
541 | NSDictionary *dataResult = [NSJSONSerialization JSONObjectWithData:data options: NSJSONReadingAllowFragments error: &error]; | 618 | NSDictionary *dataResult = [NSJSONSerialization JSONObjectWithData:data options: NSJSONReadingAllowFragments error: &error]; |
542 | NSLog(@"%@", dataResult); | 619 | NSLog(@"%@", dataResult); |
543 | int status = [dataResult[@"status"] intValue]; | 620 | int status = [dataResult[@"status"] intValue]; |
544 | if (status == 1) { // status = 1 success | 621 | if (status == 1) { // status = 1 success |
545 | if(dataResult[@"result"] != nil) { | 622 | if(dataResult[@"result"] != nil) { |
546 | NSArray * array = dataResult[@"result"]; | 623 | NSArray * array = dataResult[@"result"]; |
547 | NSMutableArray * arrayTweets = [[NSMutableArray alloc] init]; | 624 | NSMutableArray * arrayTweets = [[NSMutableArray alloc] init]; |
548 | for(NSDictionary * dict in array) { | 625 | for(NSDictionary * dict in array) { |
549 | GroupObject * object = [[GroupObject alloc] initWithData:dict]; | 626 | GroupObject * object = [[GroupObject alloc] initWithData:dict]; |
550 | [arrayTweets addObject:object]; | 627 | [arrayTweets addObject:object]; |
551 | } | 628 | } |
552 | completion(arrayTweets, nil); | 629 | completion(arrayTweets, nil); |
553 | } | 630 | } |
554 | else { | 631 | else { |
555 | NSError *errorObject = [NSError errorWithDomain:@"LifeLog_Domain" code:-1 userInfo:@{@"message":@"Unknown Error"}]; | 632 | NSError *errorObject = [NSError errorWithDomain:@"LifeLog_Domain" code:-1 userInfo:@{@"message":@"Unknown Error"}]; |
556 | completion(nil, errorObject); | 633 | completion(nil, errorObject); |
557 | } | 634 | } |
558 | } | 635 | } |
559 | else { | 636 | else { |
560 | NSString *message = dataResult[@"message"]; | 637 | NSString *message = dataResult[@"message"]; |
561 | NSError *errorObject = [NSError errorWithDomain:@"LifeLog_Domain" code:-1 userInfo:@{@"message":message}]; | 638 | NSError *errorObject = [NSError errorWithDomain:@"LifeLog_Domain" code:-1 userInfo:@{@"message":message}]; |
562 | completion(nil, errorObject); | 639 | completion(nil, errorObject); |
563 | } | 640 | } |
564 | } | 641 | } |
565 | else | 642 | else |
566 | { | 643 | { |
567 | completion(nil, error); | 644 | completion(nil, error); |
568 | } | 645 | } |
569 | }]; | 646 | }]; |
570 | } | 647 | } |
571 | 648 | ||
649 | #pragma mark - Common API | ||
650 | - (void)refreshToken: (NSString *)userID CompletionHandler:(void (^)(NSString *, NSError *))completion { | ||
651 | [self _request:[kServerAddress stringByAppendingFormat: @"refreshToken"] method:@"POST" token:@"" paras:@{@"userId":userID} completion:^(NSData *data, NSError *error) { | ||
652 | |||
653 | if (completion == NULL) { | ||
654 | return ; | ||
655 | } | ||
656 | |||
657 | if (error == nil) | ||
658 | { | ||
659 | NSDictionary *dataResult = [NSJSONSerialization JSONObjectWithData:data options: NSJSONReadingAllowFragments error: &error]; | ||
660 | |||
661 | int status = [dataResult[@"status"] intValue]; | ||
662 | if (status == 1) { // status = 1 success | ||
663 | NSArray *arrayResult = dataResult[@"result"]; | ||
664 | if (arrayResult.count > 0) { | ||
665 | NSString *token = arrayResult[0]; | ||
666 | completion(token, nil); | ||
667 | } | ||
668 | else { | ||
669 | NSError *errorObject = [NSError errorWithDomain:@"LifeLog_Domain" code:-1 userInfo:@{@"message":@"Unknown Error"}]; | ||
670 | completion(nil, errorObject); | ||
671 | } | ||
672 | |||
673 | } | ||
674 | else { // status = 0 error | ||
675 | NSString *message = dataResult[@"message"]; | ||
676 | if (message == nil) { | ||
677 | message = @"Unknown error"; | ||
678 | } | ||
679 | NSError *loginFaild = [NSError errorWithDomain:@"LifeLog_Domain" code:-1 userInfo:@{@"message":message}]; | ||
680 | completion(nil, loginFaild); | ||
681 | } | ||
682 | } | ||
683 | else | ||
684 | { | ||
685 | completion(nil, error); | ||
686 | } | ||
687 | }]; | ||
688 | } | ||
689 | |||
572 | #pragma mark - Private Function | 690 | #pragma mark - Private Function |
573 | - (BOOL) checkToken:(NSString *)message { | 691 | - (void) checkToken { |
574 | if ([message isEqualToString:@"Token is invalid"]) { | 692 | // [[NSNotificationCenter defaultCenter] postNotificationName:kNotificationToken object:nil]; |
575 | [[NSNotificationCenter defaultCenter] postNotificationName:kNotificationToken object:nil]; | 693 | NSData *data = [[NSUserDefaults standardUserDefaults] objectForKey:kUser]; |
576 | return YES; | 694 | User *user = (User *)[NSKeyedUnarchiver unarchiveObjectWithData:data]; |
695 | if (user != nil) { | ||
696 | [self refreshToken:user.user_id CompletionHandler:^(NSString *token, NSError *error) { | ||
697 | if (error == nil) { | ||
698 | [[NSUserDefaults standardUserDefaults] setObject:token forKey:kToken]; | ||
699 | [[NSUserDefaults standardUserDefaults] synchronize]; | ||
700 | } | ||
701 | }]; | ||
577 | } | 702 | } |
578 | else { | ||
579 | return NO; | ||
580 | } | ||
581 | } | 703 | } |
582 | - (NSData *) _encodeDictionary: (NSDictionary *) dictionary | 704 | - (NSData *) _encodeDictionary: (NSDictionary *) dictionary |
583 | { | 705 | { |
584 | NSMutableArray *parts = [[NSMutableArray alloc] init]; | 706 | NSMutableArray *parts = [[NSMutableArray alloc] init]; |
585 | for (id key in dictionary) | 707 | for (id key in dictionary) |
586 | { | 708 | { |
587 | NSString *encodedValue = [[dictionary[key] description] urlencode]; | 709 | NSString *encodedValue = [[dictionary[key] description] urlencode]; |
588 | NSString *encodedKey = [[key description] urlencode];//[[key description] stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding]; | 710 | NSString *encodedKey = [[key description] urlencode];//[[key description] stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding]; |
589 | NSString *part = [NSString stringWithFormat: @"%@=%@", encodedKey, encodedValue]; | 711 | NSString *part = [NSString stringWithFormat: @"%@=%@", encodedKey, encodedValue]; |
590 | [parts addObject:part]; | 712 | [parts addObject:part]; |
591 | } | 713 | } |
592 | NSString *encodedDictionary = [parts componentsJoinedByString:@"&"]; | 714 | NSString *encodedDictionary = [parts componentsJoinedByString:@"&"]; |
593 | return [encodedDictionary dataUsingEncoding: NSUTF8StringEncoding]; | 715 | return [encodedDictionary dataUsingEncoding: NSUTF8StringEncoding]; |
594 | } | 716 | } |
595 | 717 | ||
596 | - (NSURLSessionDataTask *) _request:(NSString *)address method:(NSString *)method token:(NSString *) token paras:(NSDictionary *)paras completion:(void (^)(NSData *data, NSError *error))completion | 718 | - (NSURLSessionDataTask *) _request:(NSString *)address method:(NSString *)method token:(NSString *) token paras:(NSDictionary *)paras completion:(void (^)(NSData *data, NSError *error))completion |
597 | { | 719 | { |
598 | NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL: [NSURL URLWithString:address]]; | 720 | NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL: [NSURL URLWithString:address]]; |
599 | request.HTTPMethod = method; | 721 | request.HTTPMethod = method; |
600 | [request setValue: @"application/json" forHTTPHeaderField: @"Accept"]; | 722 | [request setValue: @"application/json" forHTTPHeaderField: @"Accept"]; |
601 | [request setValue: @"application/json" forHTTPHeaderField: @"Content-Type"]; | 723 | [request setValue: @"application/json" forHTTPHeaderField: @"Content-Type"]; |
602 | if(token != nil && ![token isEqual: @""]) { | 724 | if(token != nil && ![token isEqual: @""]) { |
603 | [request setValue: token forHTTPHeaderField: @"token"]; | 725 | [request setValue: token forHTTPHeaderField: @"token"]; |
604 | } | 726 | } |
605 | [request setTimeoutInterval:self.timeOutInterval]; | 727 | [request setTimeoutInterval:self.timeOutInterval]; |
606 | 728 | ||
607 | if (paras != nil) | 729 | if (paras != nil) |
608 | { | 730 | { |
609 | NSData *encodedData = [self _encodeDictionary: paras]; | 731 | NSData *encodedData = [self _encodeDictionary: paras]; |
610 | [request setValue: [NSString stringWithFormat: @"%lu", (unsigned long) encodedData.length] forHTTPHeaderField: @"Content-Length"]; | 732 | [request setValue: [NSString stringWithFormat: @"%lu", (unsigned long) encodedData.length] forHTTPHeaderField: @"Content-Length"]; |
611 | [request setValue: @"application/x-www-form-urlencoded charset=utf-8" forHTTPHeaderField: @"Content-Type"]; | 733 | [request setValue: @"application/x-www-form-urlencoded charset=utf-8" forHTTPHeaderField: @"Content-Type"]; |
612 | [request setHTTPBody: encodedData]; | 734 | [request setHTTPBody: encodedData]; |
613 | } | 735 | } |
614 | 736 | ||
615 | NSURLSession *session = [NSURLSession sharedSession]; | 737 | NSURLSession *session = [NSURLSession sharedSession]; |
616 | NSURLSessionDataTask *task = [session dataTaskWithRequest:request | 738 | NSURLSessionDataTask *task = [session dataTaskWithRequest:request |
617 | completionHandler: | 739 | completionHandler: |
618 | ^(NSData *data, NSURLResponse *response, NSError *error) { | 740 | ^(NSData *data, NSURLResponse *response, NSError *error) { |
619 | if (completion == NULL) { | 741 | if (completion == NULL) { |
620 | return ; | 742 | return ; |
621 | } | 743 | } |
622 | if (error == nil) | 744 | if (error == nil) |
623 | { | 745 | { |
624 | completion(data, nil); | 746 | completion(data, nil); |
625 | } | 747 | } |
626 | else | 748 | else |
627 | { | 749 | { |
628 | completion(nil, error); | 750 | completion(nil, error); |
629 | } | 751 | } |
630 | }]; | 752 | }]; |
631 | [task resume]; | 753 | [task resume]; |
632 | return task; | 754 | return task; |
755 | } | ||
756 | |||
757 | -(void)waitUntilDone:(void(^)(void))waitBlock { | ||
758 | //use your statement or call method here | ||
759 | if(waitBlock){ | ||
760 | waitBlock(); | ||
761 | } | ||
633 | } | 762 | } |