Commit 920357ae44c40d3c5811159e8824122ccf272148

Authored by phong
1 parent 46f6779bfd
Exists in master

fix bug call request api

Showing 2 changed files with 4 additions and 1 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 maxRequest = 20; 18 static NSInteger maxRequest = 20;
19 static NSInteger numberTotal = 10000; 19 static NSInteger numberTotal = 10000;
20 20
21 @interface HomeViewController () 21 @interface HomeViewController ()
22 { 22 {
23 MBProgressHUD *progressHud; 23 MBProgressHUD *progressHud;
24 NSInteger targetStep; 24 NSInteger targetStep;
25 } 25 }
26 @property (nonatomic, weak) IBOutlet UILabel *lblTitle; 26 @property (nonatomic, weak) IBOutlet UILabel *lblTitle;
27 @property (nonatomic, weak) IBOutlet UIImageView *avatar; 27 @property (nonatomic, weak) IBOutlet UIImageView *avatar;
28 @property (nonatomic, weak) IBOutlet UILabel *lblDateCurrent; 28 @property (nonatomic, weak) IBOutlet UILabel *lblDateCurrent;
29 @property (nonatomic, weak) IBOutlet UILabel *lblValueStep; 29 @property (nonatomic, weak) IBOutlet UILabel *lblValueStep;
30 @property (nonatomic, weak) IBOutlet UILabel *lblUnitStep; 30 @property (nonatomic, weak) IBOutlet UILabel *lblUnitStep;
31 @property (nonatomic, weak) IBOutlet UILabel *lblValueStepOther; 31 @property (nonatomic, weak) IBOutlet UILabel *lblValueStepOther;
32 @property (nonatomic, weak) IBOutlet UILabel *lblPercent; 32 @property (nonatomic, weak) IBOutlet UILabel *lblPercent;
33 @property (nonatomic, weak) IBOutlet UILabel *lblNotice; 33 @property (nonatomic, weak) IBOutlet UILabel *lblNotice;
34 @property (weak, nonatomic) IBOutlet UISegmentedControl *segmentHome; 34 @property (weak, nonatomic) IBOutlet UISegmentedControl *segmentHome;
35 35
36 @property (nonatomic, strong) CMPedometer *pedometer; 36 @property (nonatomic, strong) CMPedometer *pedometer;
37 @property (nonatomic, strong) CMMotionActivityManager *motionActivityManager; 37 @property (nonatomic, strong) CMMotionActivityManager *motionActivityManager;
38 @property (nonatomic, strong) NSOperationQueue *operationQueue; 38 @property (nonatomic, strong) NSOperationQueue *operationQueue;
39 @property (nonatomic, strong) NSTimer *timer; 39 @property (nonatomic, strong) NSTimer *timer;
40 @property (nonatomic, assign) NSInteger bike; 40 @property (nonatomic, assign) NSInteger bike;
41 @property (nonatomic, assign) NSInteger walking; 41 @property (nonatomic, assign) NSInteger walking;
42 @property (nonatomic, assign) NSInteger running; 42 @property (nonatomic, assign) NSInteger running;
43 @property (nonatomic, strong) NSDate *dateCurrent; 43 @property (nonatomic, strong) NSDate *dateCurrent;
44 44
45 @property (nonatomic, assign) int totalRequest; 45 @property (nonatomic, assign) int totalRequest;
46 @property (nonatomic, assign) int countComplete; 46 @property (nonatomic, assign) int countComplete;
47 @property (nonatomic, assign) int currentIndex; 47 @property (nonatomic, assign) int currentIndex;
48 48
49 @end 49 @end
50 50
51 @implementation HomeViewController 51 @implementation HomeViewController
52 52
53 - (void)viewDidLoad { 53 - (void)viewDidLoad {
54 [super viewDidLoad]; 54 [super viewDidLoad];
55 55
56 self.lblTitle.text = NSLocalizedString(@"lifelog.home.title", nil); 56 self.lblTitle.text = NSLocalizedString(@"lifelog.home.title", nil);
57 57
58 [self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.topLayoutGuide attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:self.lblTitle attribute:NSLayoutAttributeTop multiplier:1 constant:0]]; 58 [self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.topLayoutGuide attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:self.lblTitle attribute:NSLayoutAttributeTop multiplier:1 constant:0]];
59 59
60 self.avatar.backgroundColor = [UIColor whiteColor]; 60 self.avatar.backgroundColor = [UIColor whiteColor];
61 self.avatar.layer.borderWidth = 2.0f; 61 self.avatar.layer.borderWidth = 2.0f;
62 self.avatar.layer.borderColor = [[UIColor whiteColor] CGColor]; 62 self.avatar.layer.borderColor = [[UIColor whiteColor] CGColor];
63 self.avatar.layer.cornerRadius = self.avatar.frame.size.width/2.0f; 63 self.avatar.layer.cornerRadius = self.avatar.frame.size.width/2.0f;
64 self.avatar.layer.masksToBounds = YES; 64 self.avatar.layer.masksToBounds = YES;
65 NSData *data = [[NSUserDefaults standardUserDefaults] objectForKey:kUser]; 65 NSData *data = [[NSUserDefaults standardUserDefaults] objectForKey:kUser];
66 User *user = (User *)[NSKeyedUnarchiver unarchiveObjectWithData:data]; 66 User *user = (User *)[NSKeyedUnarchiver unarchiveObjectWithData:data];
67 if (user != nil) { 67 if (user != nil) {
68 NSString *linkImage = [NSString stringWithFormat:@"%@%@", kServerAddress, user.profile_image]; 68 NSString *linkImage = [NSString stringWithFormat:@"%@%@", kServerAddress, user.profile_image];
69 NSURL *urlImage = [NSURL URLWithString:linkImage]; 69 NSURL *urlImage = [NSURL URLWithString:linkImage];
70 NSURLSessionConfiguration *sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration]; 70 NSURLSessionConfiguration *sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration];
71 sessionConfig.timeoutIntervalForRequest = 30.0; 71 sessionConfig.timeoutIntervalForRequest = 30.0;
72 sessionConfig.timeoutIntervalForResource = 60.0; 72 sessionConfig.timeoutIntervalForResource = 60.0;
73 sessionConfig.HTTPMaximumConnectionsPerHost = 20; 73 sessionConfig.HTTPMaximumConnectionsPerHost = 20;
74 sessionConfig.allowsCellularAccess = YES; 74 sessionConfig.allowsCellularAccess = YES;
75 HomeViewController __weak *weakSelf = self; 75 HomeViewController __weak *weakSelf = self;
76 NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfig]; 76 NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfig];
77 NSURLSessionDataTask *downloadPhotoTask = [session 77 NSURLSessionDataTask *downloadPhotoTask = [session
78 dataTaskWithURL:urlImage completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { 78 dataTaskWithURL:urlImage completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
79 if (weakSelf == nil) 79 if (weakSelf == nil)
80 { 80 {
81 return; 81 return;
82 } 82 }
83 if (error == nil) { 83 if (error == nil) {
84 UIImage *image = [[UIImage alloc] initWithData:data]; 84 UIImage *image = [[UIImage alloc] initWithData:data];
85 [[NSOperationQueue mainQueue] addOperationWithBlock:^{ 85 [[NSOperationQueue mainQueue] addOperationWithBlock:^{
86 weakSelf.avatar.image = image; 86 weakSelf.avatar.image = image;
87 }]; 87 }];
88 } 88 }
89 }]; 89 }];
90 [downloadPhotoTask resume]; 90 [downloadPhotoTask resume];
91 } 91 }
92 92
93 self.lblNotice.text = NSLocalizedString(@"lifelog.home.notice", nil); 93 self.lblNotice.text = NSLocalizedString(@"lifelog.home.notice", nil);
94 94
95 _dateCurrent = [NSDate date]; 95 _dateCurrent = [NSDate date];
96 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)]; 96 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)];
97 97
98 self.lblUnitStep.text = NSLocalizedString(@"lifelog.home.unit.step", nil); 98 self.lblUnitStep.text = NSLocalizedString(@"lifelog.home.unit.step", nil);
99 99
100 if ([CMPedometer isStepCountingAvailable]) { 100 if ([CMPedometer isStepCountingAvailable]) {
101 _pedometer = [[CMPedometer alloc] init]; 101 _pedometer = [[CMPedometer alloc] init];
102 } 102 }
103 if ([CMMotionActivityManager isActivityAvailable]) { 103 if ([CMMotionActivityManager isActivityAvailable]) {
104 _motionActivityManager = [[CMMotionActivityManager alloc] init]; 104 _motionActivityManager = [[CMMotionActivityManager alloc] init];
105 } 105 }
106 _operationQueue = [[NSOperationQueue alloc] init]; 106 _operationQueue = [[NSOperationQueue alloc] init];
107 _bike = 0; 107 _bike = 0;
108 _walking = 0; 108 _walking = 0;
109 _running = 0; 109 _running = 0;
110 _segmentHome.selectedSegmentIndex = 1; 110 _segmentHome.selectedSegmentIndex = 1;
111 _totalRequest = 0; 111 _totalRequest = 0;
112 _countComplete = 0; 112 _countComplete = 0;
113 113
114 progressHud = [MBProgressHUD showHUDAddedTo:self.view animated:YES]; 114 progressHud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
115 progressHud.mode = MBProgressHUDModeIndeterminate; 115 progressHud.mode = MBProgressHUDModeIndeterminate;
116 progressHud.detailsLabel.text = NSLocalizedString(@"lifelog.home.progressHud.title", nil); 116 progressHud.detailsLabel.text = NSLocalizedString(@"lifelog.home.progressHud.title", nil);
117 // [self saveDataStep7LastDay]; 117 // [self saveDataStep7LastDay];
118 targetStep = numberTotal; 118 targetStep = numberTotal;
119 } 119 }
120 120
121 - (void)viewWillAppear:(BOOL)animated { 121 - (void)viewWillAppear:(BOOL)animated {
122 [super viewWillAppear:animated]; 122 [super viewWillAppear:animated];
123 NSDate *dateNow = [NSDate date]; 123 NSDate *dateNow = [NSDate date];
124 [self saveStepForDay:dateNow]; 124 [self saveStepForDay:dateNow];
125 } 125 }
126 126
127 - (void)requestTopByDate:(NSDate *)date { 127 - (void)requestTopByDate:(NSDate *)date {
128 NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 128 NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
129 [dateFormatter setDateFormat:@"yyyy-MM-dd"]; 129 [dateFormatter setDateFormat:@"yyyy-MM-dd"];
130 NSString *dateString = [dateFormatter stringFromDate:date]; 130 NSString *dateString = [dateFormatter stringFromDate:date];
131 [progressHud showAnimated:YES]; 131 [progressHud showAnimated:YES];
132 [progressHud setHidden:NO]; 132 [progressHud setHidden:NO];
133 HomeViewController __weak *weakSelf = self; 133 HomeViewController __weak *weakSelf = self;
134 int mode = 1; 134 int mode = 1;
135 switch (_segmentHome.selectedSegmentIndex) { 135 switch (_segmentHome.selectedSegmentIndex) {
136 case 0: 136 case 0:
137 mode = 3; 137 mode = 3;
138 break; 138 break;
139 139
140 case 1: 140 case 1:
141 mode = 1; 141 mode = 1;
142 break; 142 break;
143 143
144 case 2: 144 case 2:
145 mode = 2; 145 mode = 2;
146 break; 146 break;
147 147
148 default: 148 default:
149 break; 149 break;
150 } 150 }
151 [[ServerAPI server] requestTopWithMode:mode andDate:dateString CompletionHandler:^(TopObject *topObject, NSError *error) { 151 [[ServerAPI server] requestTopWithMode:mode andDate:dateString CompletionHandler:^(TopObject *topObject, NSError *error) {
152 if(weakSelf == nil) { 152 if(weakSelf == nil) {
153 return ; 153 return ;
154 } 154 }
155 if (error == nil) { 155 if (error == nil) {
156 NSLog(@"TopObject: %@", topObject); 156 NSLog(@"TopObject: %@", topObject);
157 dispatch_async(dispatch_get_main_queue(), ^{ 157 dispatch_async(dispatch_get_main_queue(), ^{
158 [weakSelf updateStepUI:topObject.targetInfor]; 158 [weakSelf updateStepUI:topObject.targetInfor];
159 }); 159 });
160 } 160 }
161 else { 161 else {
162 dispatch_async(dispatch_get_main_queue(), ^{ 162 dispatch_async(dispatch_get_main_queue(), ^{
163 NSString *message = [error.userInfo objectForKey:@"message"]; 163 NSString *message = [error.userInfo objectForKey:@"message"];
164 [Utilities showErrorMessage:message withViewController:weakSelf]; 164 [Utilities showErrorMessage:message withViewController:weakSelf];
165 }); 165 });
166 } 166 }
167 dispatch_async(dispatch_get_main_queue(), ^{ 167 dispatch_async(dispatch_get_main_queue(), ^{
168 [progressHud setHidden:YES]; 168 [progressHud setHidden:YES];
169 }); 169 });
170 }]; 170 }];
171 } 171 }
172 172
173 - (void)viewWillDisappear:(BOOL)animated { 173 - (void)viewWillDisappear:(BOOL)animated {
174 [super viewWillDisappear:animated]; 174 [super viewWillDisappear:animated];
175 } 175 }
176 176
177 - (void)didReceiveMemoryWarning { 177 - (void)didReceiveMemoryWarning {
178 [super didReceiveMemoryWarning]; 178 [super didReceiveMemoryWarning];
179 // Dispose of any resources that can be recreated. 179 // Dispose of any resources that can be recreated.
180 } 180 }
181 181
182 #pragma mark - IBAction 182 #pragma mark - IBAction
183 - (IBAction)menuButtonTouchUpInside:(id)sender 183 - (IBAction)menuButtonTouchUpInside:(id)sender
184 { 184 {
185 185
186 } 186 }
187 187
188 - (IBAction)todayButtonTouchUpInside:(id)sender 188 - (IBAction)todayButtonTouchUpInside:(id)sender
189 { 189 {
190 TodayViewController *todayVC = [[TodayViewController alloc] initWithNibName:@"TodayViewController" bundle:nil]; 190 TodayViewController *todayVC = [[TodayViewController alloc] initWithNibName:@"TodayViewController" bundle:nil];
191 todayVC.targetStep = targetStep; 191 todayVC.targetStep = targetStep;
192 [self.navigationController pushViewController:todayVC animated:YES]; 192 [self.navigationController pushViewController:todayVC animated:YES];
193 } 193 }
194 194
195 - (IBAction)leftButtonTouchUpInside:(id)sender 195 - (IBAction)leftButtonTouchUpInside:(id)sender
196 { 196 {
197 self.dateCurrent = [self.dateCurrent dateByAddingTimeInterval:-(24*60*60)]; 197 self.dateCurrent = [self.dateCurrent dateByAddingTimeInterval:-(24*60*60)];
198 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)]; 198 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)];
199 [self resetStepUI]; 199 [self resetStepUI];
200 [self saveStepForDay:self.dateCurrent]; 200 [self saveStepForDay:self.dateCurrent];
201 } 201 }
202 202
203 - (IBAction)rightButtonTouchUpInside:(id)sender 203 - (IBAction)rightButtonTouchUpInside:(id)sender
204 { 204 {
205 self.dateCurrent = [self.dateCurrent dateByAddingTimeInterval:24*60*60]; 205 self.dateCurrent = [self.dateCurrent dateByAddingTimeInterval:24*60*60];
206 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)]; 206 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)];
207 [self resetStepUI]; 207 [self resetStepUI];
208 //[self saveStepForDay:self.dateCurrent]; 208 //[self saveStepForDay:self.dateCurrent];
209 [self requestTopByDate:self.dateCurrent]; 209 [self requestTopByDate:self.dateCurrent];
210 } 210 }
211 211
212 - (IBAction)segmentValueChange:(id)sender { 212 - (IBAction)segmentValueChange:(id)sender {
213 [self resetStepUI]; 213 [self resetStepUI];
214 [self requestTopByDate:self.dateCurrent]; 214 [self requestTopByDate:self.dateCurrent];
215 } 215 }
216 216
217 #pragma mark - Functions Private 217 #pragma mark - Functions Private
218 - (void)saveStepForDay:(NSDate *)date 218 - (void)saveStepForDay:(NSDate *)date
219 { 219 {
220 if ([CMMotionActivityManager isActivityAvailable]) { 220 if ([CMMotionActivityManager isActivityAvailable]) {
221 [progressHud showAnimated:YES]; 221 [progressHud showAnimated:YES];
222 [progressHud setHidden:NO]; 222 [progressHud setHidden:NO];
223 self.bike = 0; 223 self.bike = 0;
224 self.walking = 0; 224 self.walking = 0;
225 self.running = 0; 225 self.running = 0;
226 NSDate *startDate = [date beginningAtMidnightOfDay]; 226 NSDate *startDate = [date beginningAtMidnightOfDay];
227 NSDate *endDate = [startDate dateByAddingTimeInterval:(24*60*60 - 1)]; 227 NSDate *endDate = [startDate dateByAddingTimeInterval:(24*60*60 - 1)];
228 228
229 HomeViewController __weak *weakSelf = self; 229 HomeViewController __weak *weakSelf = self;
230 dispatch_queue_t myQueue = dispatch_queue_create("mobileworld.jp.lifelog.forDay", NULL); 230 dispatch_queue_t myQueue = dispatch_queue_create("mobileworld.jp.lifelog.forDay", NULL);
231 dispatch_async(myQueue, ^{ 231 dispatch_async(myQueue, ^{
232 if (weakSelf == nil) { 232 if (weakSelf == nil) {
233 return ; 233 return ;
234 } 234 }
235 235
236 [weakSelf.motionActivityManager queryActivityStartingFromDate:startDate toDate:endDate toQueue:_operationQueue withHandler:^(NSArray<CMMotionActivity *> * _Nullable activities, NSError * _Nullable error) { 236 [weakSelf.motionActivityManager queryActivityStartingFromDate:startDate toDate:endDate toQueue:_operationQueue withHandler:^(NSArray<CMMotionActivity *> * _Nullable activities, NSError * _Nullable error) {
237 if (error || activities.count <= 0) { 237 if (error || activities.count <= 0) {
238 dispatch_async(dispatch_get_main_queue(), ^{ 238 dispatch_async(dispatch_get_main_queue(), ^{
239 [weakSelf updateStepUI]; 239 [weakSelf updateStepUI];
240 }); 240 });
241 return ; 241 return ;
242 } 242 }
243 // set EndDate 243 // set EndDate
244 NSMutableArray *arrayActivities = [[NSMutableArray alloc] init]; 244 NSMutableArray *arrayActivities = [[NSMutableArray alloc] init];
245 for (int i = 0; i < activities.count; i++) { 245 for (int i = 0; i < activities.count; i++) {
246 CMMotionActivity *activity = [activities objectAtIndex:i]; 246 CMMotionActivity *activity = [activities objectAtIndex:i];
247 CMMotionActivityExtra *activityExtra = [[CMMotionActivityExtra alloc] init]; 247 CMMotionActivityExtra *activityExtra = [[CMMotionActivityExtra alloc] init];
248 activityExtra.activity = activity; 248 activityExtra.activity = activity;
249 if (i == activities.count - 1) { 249 if (i == activities.count - 1) {
250 activityExtra.endDate = endDate; 250 activityExtra.endDate = endDate;
251 } 251 }
252 else { 252 else {
253 CMMotionActivity *activityNext = [activities objectAtIndex:i+1]; 253 CMMotionActivity *activityNext = [activities objectAtIndex:i+1];
254 activityExtra.endDate = activityNext.startDate; 254 activityExtra.endDate = activityNext.startDate;
255 } 255 }
256 [arrayActivities addObject:activityExtra]; 256 [arrayActivities addObject:activityExtra];
257 } 257 }
258 // PhongNV 258 // PhongNV
259 weakSelf.currentIndex = 0; 259 weakSelf.currentIndex = 0;
260 [weakSelf save20objectOfActivityExtras:arrayActivities]; 260 [weakSelf save20objectOfActivityExtras:arrayActivities];
261 }]; 261 }];
262 }); 262 });
263 } 263 }
264 } 264 }
265 265
266 - (void)complete20Request:(NSArray *)activities { 266 - (void)complete20Request:(NSArray *)activities {
267 if (self.totalRequest == self.countComplete) { 267 if (self.totalRequest == self.countComplete) {
268 self.totalRequest = 0; 268 self.totalRequest = 0;
269 self.countComplete = 0; 269 self.countComplete = 0;
270 self.currentIndex++; 270 self.currentIndex++;
271 [self save20objectOfActivityExtras:activities]; 271 [self save20objectOfActivityExtras:activities];
272 } 272 }
273 } 273 }
274 - (void)save20objectOfActivityExtras:(NSArray *)activities 274 - (void)save20objectOfActivityExtras:(NSArray *)activities
275 { 275 {
276 int result = floor(activities.count / maxRequest); 276 int result = floor(activities.count / maxRequest);
277 if (activities.count <= 0 || self.currentIndex > result) { 277 if (activities.count <= 0 || self.currentIndex > result) {
278 self.totalRequest = 0; 278 self.totalRequest = 0;
279 self.countComplete = 0; 279 self.countComplete = 0;
280 self.currentIndex = 0; 280 self.currentIndex = 0;
281 dispatch_async(dispatch_get_main_queue(), ^{ 281 dispatch_async(dispatch_get_main_queue(), ^{
282 [self updateStepUI]; 282 [self updateStepUI];
283 }); 283 });
284 return; 284 return;
285 } 285 }
286 286
287 HomeViewController __weak *weakSelf = self; 287 HomeViewController __weak *weakSelf = self;
288 for (NSInteger index = self.currentIndex*maxRequest; index < self.currentIndex*maxRequest + maxRequest; index++) { 288 for (NSInteger index = self.currentIndex*maxRequest; index < self.currentIndex*maxRequest + maxRequest; index++) {
289 if ((self.currentIndex*maxRequest + maxRequest) >= activities.count) { 289 if ((self.currentIndex*maxRequest + maxRequest) >= activities.count) {
290 self.totalRequest = (int)(activities.count - self.currentIndex*maxRequest); 290 self.totalRequest = (int)(activities.count - self.currentIndex*maxRequest);
291 if (self.totalRequest <= 0) {
292 [weakSelf complete20Request:activities];
293 }
291 } 294 }
292 else { 295 else {
293 self.totalRequest = (int)maxRequest; 296 self.totalRequest = (int)maxRequest;
294 } 297 }
295 if (index < activities.count) { 298 if (index < activities.count) {
296 CMMotionActivityExtra *activityExtra = [activities objectAtIndex:index]; 299 CMMotionActivityExtra *activityExtra = [activities objectAtIndex:index];
297 [self.pedometer queryPedometerDataFromDate:activityExtra.activity.startDate toDate:activityExtra.endDate withHandler:^(CMPedometerData * _Nullable pedometerData, NSError * _Nullable error) { 300 [self.pedometer queryPedometerDataFromDate:activityExtra.activity.startDate toDate:activityExtra.endDate withHandler:^(CMPedometerData * _Nullable pedometerData, NSError * _Nullable error) {
298 if (weakSelf == nil) { 301 if (weakSelf == nil) {
299 return ; 302 return ;
300 } 303 }
301 NSInteger numberStep = [pedometerData.numberOfSteps integerValue]; 304 NSInteger numberStep = [pedometerData.numberOfSteps integerValue];
302 int mode = 1; 305 int mode = 1;
303 if (activityExtra.activity.cycling) { 306 if (activityExtra.activity.cycling) {
304 mode = 3; 307 mode = 3;
305 } 308 }
306 else if (activityExtra.activity.walking) { 309 else if (activityExtra.activity.walking) {
307 mode = 1; 310 mode = 1;
308 } 311 }
309 else if (activityExtra.activity.running) { 312 else if (activityExtra.activity.running) {
310 mode = 2; 313 mode = 2;
311 } 314 }
312 else { 315 else {
313 // unknown 316 // unknown
314 } 317 }
315 // save step to server 318 // save step to server
316 if (numberStep > 0) { 319 if (numberStep > 0) {
317 NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 320 NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
318 [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"]; 321 [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
319 NSString *dateBegin = [dateFormatter stringFromDate:activityExtra.activity.startDate]; 322 NSString *dateBegin = [dateFormatter stringFromDate:activityExtra.activity.startDate];
320 NSString *dateEnd = [dateFormatter stringFromDate:activityExtra.endDate]; 323 NSString *dateEnd = [dateFormatter stringFromDate:activityExtra.endDate];
321 [[ServerAPI server] requestCreateLog:mode withStep:(int)numberStep startDate:dateBegin endDate:dateEnd CompletionHandler:^(NSError *error) { 324 [[ServerAPI server] requestCreateLog:mode withStep:(int)numberStep startDate:dateBegin endDate:dateEnd CompletionHandler:^(NSError *error) {
322 if (error) { 325 if (error) {
323 NSLog(@"Error: %@", error); 326 NSLog(@"Error: %@", error);
324 } 327 }
325 weakSelf.countComplete++; 328 weakSelf.countComplete++;
326 [weakSelf complete20Request:activities]; 329 [weakSelf complete20Request:activities];
327 }]; 330 }];
328 } 331 }
329 else { 332 else {
330 weakSelf.countComplete++; 333 weakSelf.countComplete++;
331 [weakSelf complete20Request:activities]; 334 [weakSelf complete20Request:activities];
332 } 335 }
333 }]; 336 }];
334 } 337 }
335 } 338 }
336 } 339 }
337 340
338 - (void)updateStepUI 341 - (void)updateStepUI
339 { 342 {
340 [self requestTopByDate:self.dateCurrent]; 343 [self requestTopByDate:self.dateCurrent];
341 } 344 }
342 345
343 - (void)saveDataStep7LastDay 346 - (void)saveDataStep7LastDay
344 { 347 {
345 NSDate *dateNow = [NSDate date]; 348 NSDate *dateNow = [NSDate date];
346 for (int index = 0; index < 7; index++) { 349 for (int index = 0; index < 7; index++) {
347 dateNow = [dateNow dateByAddingTimeInterval:-(24*60*60)]; 350 dateNow = [dateNow dateByAddingTimeInterval:-(24*60*60)];
348 [self saveStepByDate:dateNow]; 351 [self saveStepByDate:dateNow];
349 } 352 }
350 } 353 }
351 354
352 - (void)saveStepByDate:(NSDate *)date 355 - (void)saveStepByDate:(NSDate *)date
353 { 356 {
354 if ([CMMotionActivityManager isActivityAvailable]) { 357 if ([CMMotionActivityManager isActivityAvailable]) {
355 NSDate *startDate = [date beginningAtMidnightOfDay]; 358 NSDate *startDate = [date beginningAtMidnightOfDay];
356 NSDate *endDate = [startDate dateByAddingTimeInterval:(24*60*60 - 1)]; 359 NSDate *endDate = [startDate dateByAddingTimeInterval:(24*60*60 - 1)];
357 360
358 HomeViewController __weak *weakSelf = self; 361 HomeViewController __weak *weakSelf = self;
359 dispatch_queue_t myQueue = dispatch_queue_create("mobileworld.jp.lifelog.7lastday", NULL); 362 dispatch_queue_t myQueue = dispatch_queue_create("mobileworld.jp.lifelog.7lastday", NULL);
360 dispatch_async(myQueue, ^{ 363 dispatch_async(myQueue, ^{
361 if (weakSelf == nil) { 364 if (weakSelf == nil) {
362 return ; 365 return ;
363 } 366 }
364 367
365 [weakSelf.motionActivityManager queryActivityStartingFromDate:startDate toDate:endDate toQueue:_operationQueue withHandler:^(NSArray<CMMotionActivity *> * _Nullable activities, NSError * _Nullable error) { 368 [weakSelf.motionActivityManager queryActivityStartingFromDate:startDate toDate:endDate toQueue:_operationQueue withHandler:^(NSArray<CMMotionActivity *> * _Nullable activities, NSError * _Nullable error) {
366 if (error || activities.count <= 0) { 369 if (error || activities.count <= 0) {
367 return ; 370 return ;
368 } 371 }
369 // set EndDate 372 // set EndDate
370 NSMutableArray *arrayActivities = [[NSMutableArray alloc] init]; 373 NSMutableArray *arrayActivities = [[NSMutableArray alloc] init];
371 for (int i = 0; i < activities.count; i++) { 374 for (int i = 0; i < activities.count; i++) {
372 CMMotionActivity *activity = [activities objectAtIndex:i]; 375 CMMotionActivity *activity = [activities objectAtIndex:i];
373 CMMotionActivityExtra *activityExtra = [[CMMotionActivityExtra alloc] init]; 376 CMMotionActivityExtra *activityExtra = [[CMMotionActivityExtra alloc] init];
374 activityExtra.activity = activity; 377 activityExtra.activity = activity;
375 if (i == activities.count - 1) { 378 if (i == activities.count - 1) {
376 activityExtra.endDate = endDate; 379 activityExtra.endDate = endDate;
377 } 380 }
378 else { 381 else {
379 CMMotionActivity *activityNext = [activities objectAtIndex:i+1]; 382 CMMotionActivity *activityNext = [activities objectAtIndex:i+1];
380 activityExtra.endDate = activityNext.startDate; 383 activityExtra.endDate = activityNext.startDate;
381 } 384 }
382 [arrayActivities addObject:activityExtra]; 385 [arrayActivities addObject:activityExtra];
383 } 386 }
384 387
385 for (CMMotionActivityExtra *activityExtra in arrayActivities) { 388 for (CMMotionActivityExtra *activityExtra in arrayActivities) {
386 [weakSelf.pedometer queryPedometerDataFromDate:activityExtra.activity.startDate toDate:activityExtra.endDate withHandler:^(CMPedometerData * _Nullable pedometerData, NSError * _Nullable error) { 389 [weakSelf.pedometer queryPedometerDataFromDate:activityExtra.activity.startDate toDate:activityExtra.endDate withHandler:^(CMPedometerData * _Nullable pedometerData, NSError * _Nullable error) {
387 NSInteger numberStep = [pedometerData.numberOfSteps integerValue]; 390 NSInteger numberStep = [pedometerData.numberOfSteps integerValue];
388 int mode = 1; 391 int mode = 1;
389 if (activityExtra.activity.cycling) { 392 if (activityExtra.activity.cycling) {
390 mode = 3; 393 mode = 3;
391 } 394 }
392 else if (activityExtra.activity.walking) { 395 else if (activityExtra.activity.walking) {
393 mode = 1; 396 mode = 1;
394 } 397 }
395 else if (activityExtra.activity.running) { 398 else if (activityExtra.activity.running) {
396 mode = 2; 399 mode = 2;
397 } 400 }
398 else { 401 else {
399 // unknown 402 // unknown
400 } 403 }
401 404
402 // save step to server 405 // save step to server
403 if (numberStep > 0) { 406 if (numberStep > 0) {
404 NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 407 NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
405 [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"]; 408 [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
406 NSString *dateBegin = [dateFormatter stringFromDate:activityExtra.activity.startDate]; 409 NSString *dateBegin = [dateFormatter stringFromDate:activityExtra.activity.startDate];
407 NSString *dateEnd = [dateFormatter stringFromDate:activityExtra.endDate]; 410 NSString *dateEnd = [dateFormatter stringFromDate:activityExtra.endDate];
408 [[ServerAPI server] requestCreateLog:mode withStep:(int)numberStep startDate:dateBegin endDate:dateEnd CompletionHandler:^(NSError *error) { 411 [[ServerAPI server] requestCreateLog:mode withStep:(int)numberStep startDate:dateBegin endDate:dateEnd CompletionHandler:^(NSError *error) {
409 if (error) { 412 if (error) {
410 NSLog(@"Error: %@", error); 413 NSLog(@"Error: %@", error);
411 } 414 }
412 }]; 415 }];
413 } 416 }
414 }]; 417 }];
415 } 418 }
416 }]; 419 }];
417 }); 420 });
418 } 421 }
419 } 422 }
420 423
421 - (void)updateStepUI:(TargetInfor *)targetInfor 424 - (void)updateStepUI:(TargetInfor *)targetInfor
422 { 425 {
423 NSString *stringTargetStep = [targetInfor.target_step stringByReplacingOccurrencesOfString:@"," withString:@""]; 426 NSString *stringTargetStep = [targetInfor.target_step stringByReplacingOccurrencesOfString:@"," withString:@""];
424 targetStep = [stringTargetStep integerValue]; 427 targetStep = [stringTargetStep integerValue];
425 self.lblValueStep.text = targetInfor.num_step; 428 self.lblValueStep.text = targetInfor.num_step;
426 self.lblValueStepOther.text = [NSString stringWithFormat:@"%@ %@", NSLocalizedString(@"lifelog.today.remaining.other", nil), targetInfor.remaining_step]; 429 self.lblValueStepOther.text = [NSString stringWithFormat:@"%@ %@", NSLocalizedString(@"lifelog.today.remaining.other", nil), targetInfor.remaining_step];
427 self.lblPercent.text = [NSString stringWithFormat:@"%@ %i%@", NSLocalizedString(@"lifelog.today.text.percent", nil), [targetInfor.complete_percent intValue], NSLocalizedString(@"lifelog.today.percent", nil)]; 430 self.lblPercent.text = [NSString stringWithFormat:@"%@ %i%@", NSLocalizedString(@"lifelog.today.text.percent", nil), [targetInfor.complete_percent intValue], NSLocalizedString(@"lifelog.today.percent", nil)];
428 } 431 }
429 432
430 - (void)resetStepUI 433 - (void)resetStepUI
431 { 434 {
432 self.lblValueStep.text = @""; 435 self.lblValueStep.text = @"";
433 self.lblValueStepOther.text = @""; 436 self.lblValueStepOther.text = @"";
434 self.lblPercent.text = @""; 437 self.lblPercent.text = @"";
435 } 438 }
436 439
437 @end 440 @end
438 441
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>CFBundleDisplayName</key> 7 <key>CFBundleDisplayName</key>
8 <string>LIFE_LOG</string> 8 <string>LIFE_LOG</string>
9 <key>CFBundleExecutable</key> 9 <key>CFBundleExecutable</key>
10 <string>$(EXECUTABLE_NAME)</string> 10 <string>$(EXECUTABLE_NAME)</string>
11 <key>CFBundleIdentifier</key> 11 <key>CFBundleIdentifier</key>
12 <string>$(PRODUCT_BUNDLE_IDENTIFIER)</string> 12 <string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
13 <key>CFBundleInfoDictionaryVersion</key> 13 <key>CFBundleInfoDictionaryVersion</key>
14 <string>6.0</string> 14 <string>6.0</string>
15 <key>CFBundleName</key> 15 <key>CFBundleName</key>
16 <string>$(PRODUCT_NAME)</string> 16 <string>$(PRODUCT_NAME)</string>
17 <key>CFBundlePackageType</key> 17 <key>CFBundlePackageType</key>
18 <string>APPL</string> 18 <string>APPL</string>
19 <key>CFBundleShortVersionString</key> 19 <key>CFBundleShortVersionString</key>
20 <string>1.0</string> 20 <string>1.0</string>
21 <key>CFBundleURLTypes</key> 21 <key>CFBundleURLTypes</key>
22 <array> 22 <array>
23 <dict/> 23 <dict/>
24 </array> 24 </array>
25 <key>CFBundleVersion</key> 25 <key>CFBundleVersion</key>
26 <string>1</string> 26 <string>2</string>
27 <key>LSApplicationQueriesSchemes</key> 27 <key>LSApplicationQueriesSchemes</key>
28 <array> 28 <array>
29 <string>line</string> 29 <string>line</string>
30 </array> 30 </array>
31 <key>LSRequiresIPhoneOS</key> 31 <key>LSRequiresIPhoneOS</key>
32 <true/> 32 <true/>
33 <key>NSAppTransportSecurity</key> 33 <key>NSAppTransportSecurity</key>
34 <dict> 34 <dict>
35 <key>NSAllowsArbitraryLoads</key> 35 <key>NSAllowsArbitraryLoads</key>
36 <true/> 36 <true/>
37 </dict> 37 </dict>
38 <key>NSCameraUsageDescription</key> 38 <key>NSCameraUsageDescription</key>
39 <string>to take photos and video</string> 39 <string>to take photos and video</string>
40 <key>NSLocationAlwaysUsageDescription</key> 40 <key>NSLocationAlwaysUsageDescription</key>
41 <string>This application requires location services to work</string> 41 <string>This application requires location services to work</string>
42 <key>NSLocationWhenInUseUsageDescription</key> 42 <key>NSLocationWhenInUseUsageDescription</key>
43 <string>This application requires location services to work</string> 43 <string>This application requires location services to work</string>
44 <key>NSMotionUsageDescription</key> 44 <key>NSMotionUsageDescription</key>
45 <string>$(PRODUCT_NAME) motion use</string> 45 <string>$(PRODUCT_NAME) motion use</string>
46 <key>NSPhotoLibraryUsageDescription</key> 46 <key>NSPhotoLibraryUsageDescription</key>
47 <string>to save photos and videos</string> 47 <string>to save photos and videos</string>
48 <key>UILaunchStoryboardName</key> 48 <key>UILaunchStoryboardName</key>
49 <string>LaunchScreen</string> 49 <string>LaunchScreen</string>
50 <key>UIRequiredDeviceCapabilities</key> 50 <key>UIRequiredDeviceCapabilities</key>
51 <array> 51 <array>
52 <string>armv7</string> 52 <string>armv7</string>
53 </array> 53 </array>
54 <key>UIStatusBarHidden</key> 54 <key>UIStatusBarHidden</key>
55 <true/> 55 <true/>
56 <key>UISupportedInterfaceOrientations</key> 56 <key>UISupportedInterfaceOrientations</key>
57 <array> 57 <array>
58 <string>UIInterfaceOrientationPortrait</string> 58 <string>UIInterfaceOrientationPortrait</string>
59 </array> 59 </array>
60 <key>UISupportedInterfaceOrientations~ipad</key> 60 <key>UISupportedInterfaceOrientations~ipad</key>
61 <array> 61 <array>
62 <string>UIInterfaceOrientationPortrait</string> 62 <string>UIInterfaceOrientationPortrait</string>
63 <string>UIInterfaceOrientationPortraitUpsideDown</string> 63 <string>UIInterfaceOrientationPortraitUpsideDown</string>
64 <string>UIInterfaceOrientationLandscapeLeft</string> 64 <string>UIInterfaceOrientationLandscapeLeft</string>
65 <string>UIInterfaceOrientationLandscapeRight</string> 65 <string>UIInterfaceOrientationLandscapeRight</string>
66 </array> 66 </array>
67 <key>UIViewControllerBasedStatusBarAppearance</key> 67 <key>UIViewControllerBasedStatusBarAppearance</key>
68 <false/> 68 <false/>
69 </dict> 69 </dict>
70 </plist> 70 </plist>
71 71