HomeViewController.m
14.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
//
// HomeViewController.m
// LifeLog
//
// Created by Nguyen Van Phong on 7/25/17.
// Copyright © 2017 PhongNV. All rights reserved.
//
#import "HomeViewController.h"
#import "NSDate+helper.h"
#import <CoreMotion/CoreMotion.h>
#import "CMMotionActivityExtra.h"
#import "TodayViewController.h"
#import "Utilities.h"
#import <MBProgressHUD/MBProgressHUD.h>
#import "ServerAPI.h"
static NSInteger numberTotal = 10000;
@interface HomeViewController ()
{
MBProgressHUD *progressHud;
}
@property (nonatomic, weak) IBOutlet UILabel *lblTitle;
@property (nonatomic, weak) IBOutlet UIImageView *avatar;
@property (nonatomic, weak) IBOutlet UILabel *lblDateCurrent;
@property (nonatomic, weak) IBOutlet UILabel *lblValueStep;
@property (nonatomic, weak) IBOutlet UILabel *lblUnitStep;
@property (nonatomic, weak) IBOutlet UILabel *lblValueStepOther;
@property (nonatomic, weak) IBOutlet UILabel *lblPercent;
@property (nonatomic, weak) IBOutlet UILabel *lblNotice;
@property (weak, nonatomic) IBOutlet UISegmentedControl *segmentHome;
@property (nonatomic, strong) CMPedometer *pedometer;
@property (nonatomic, strong) CMMotionActivityManager *motionActivityManager;
@property (nonatomic, strong) NSOperationQueue *operationQueue;
@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, assign) NSInteger bike;
@property (nonatomic, assign) NSInteger walking;
@property (nonatomic, assign) NSInteger running;
@property (nonatomic, strong) NSDate *dateCurrent;
//@property (nonatomic, assign) BOOL isRequesting;
@property (nonatomic, assign) int totalRequest;
@property (nonatomic, assign) int countComplete;
@end
@implementation HomeViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
self.lblTitle.text = NSLocalizedString(@"lifelog.home.title", nil);
[self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.topLayoutGuide attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:self.lblTitle attribute:NSLayoutAttributeTop multiplier:1 constant:0]];
self.avatar.backgroundColor = [UIColor whiteColor];
self.avatar.layer.borderWidth = 2.0f;
self.avatar.layer.borderColor = [[UIColor whiteColor] CGColor];
self.avatar.layer.cornerRadius = self.avatar.frame.size.width/2.0f;
self.avatar.layer.masksToBounds = YES;
NSData *data = [[NSUserDefaults standardUserDefaults] objectForKey:kUser];
User *user = (User *)[NSKeyedUnarchiver unarchiveObjectWithData:data];
if (user != nil) {
NSString *linkImage = [NSString stringWithFormat:@"%@%@", kServerAddress, user.profile_image];
NSURL *urlImage = [NSURL URLWithString:linkImage];
NSURLSessionConfiguration *sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration];
sessionConfig.timeoutIntervalForRequest = 30.0;
sessionConfig.timeoutIntervalForResource = 60.0;
sessionConfig.HTTPMaximumConnectionsPerHost = 20;
sessionConfig.allowsCellularAccess = YES;
HomeViewController __weak *weakSelf = self;
NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfig];
NSURLSessionDataTask *downloadPhotoTask = [session
dataTaskWithURL:urlImage completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (weakSelf == nil)
{
return;
}
if (error == nil) {
UIImage *image = [[UIImage alloc] initWithData:data];
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
weakSelf.avatar.image = image;
}];
}
}];
[downloadPhotoTask resume];
}
self.lblNotice.text = NSLocalizedString(@"lifelog.home.notice", nil);
_dateCurrent = [NSDate date];
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)];
self.lblUnitStep.text = NSLocalizedString(@"lifelog.home.unit.step", nil);
if ([CMPedometer isStepCountingAvailable]) {
_pedometer = [[CMPedometer alloc] init];
}
if ([CMMotionActivityManager isActivityAvailable]) {
_motionActivityManager = [[CMMotionActivityManager alloc] init];
}
_operationQueue = [[NSOperationQueue alloc] init];
_bike = 0;
_walking = 0;
_running = 0;
_segmentHome.selectedSegmentIndex = 1;
// _isRequesting = NO;
_totalRequest = 0;
_countComplete = 0;
progressHud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
progressHud.mode = MBProgressHUDModeIndeterminate;
progressHud.detailsLabel.text = NSLocalizedString(@"lifelog.home.progressHud.title", nil);
}
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
// _timer = [NSTimer scheduledTimerWithTimeInterval:1.5f target:self selector:@selector(countStep) userInfo:nil repeats:YES];
// [_timer fire];
[self countStep];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd"];
NSString *dateString = [dateFormatter stringFromDate:_dateCurrent];
HomeViewController __weak *weakSelf = self;
[[ServerAPI server] requestTopWithMode:(int)_segmentHome.selectedSegmentIndex andDate:dateString CompletionHandler:^(TopObject *topObject, NSError *error) {
if(weakSelf == nil) {
return ;
}
if (error == nil) {
NSLog(@"TopObject: %@", topObject);
}
else {
dispatch_async(dispatch_get_main_queue(), ^{
NSString *message = [error.userInfo objectForKey:@"message"];
[Utilities showErrorMessage:message withViewController:weakSelf];
});
}
}];
}
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
//[_timer invalidate];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - IBAction
- (IBAction)menuButtonTouchUpInside:(id)sender
{
}
- (IBAction)todayButtonTouchUpInside:(id)sender
{
TodayViewController *todayVC = [[TodayViewController alloc] initWithNibName:@"TodayViewController" bundle:nil];
[self.navigationController pushViewController:todayVC animated:YES];
}
- (IBAction)leftButtonTouchUpInside:(id)sender
{
self.dateCurrent = [self.dateCurrent dateByAddingTimeInterval:-(24*60*60)];
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)];
[self countStep];
}
- (IBAction)rightButtonTouchUpInside:(id)sender
{
self.dateCurrent = [self.dateCurrent dateByAddingTimeInterval:24*60*60];
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)];
[self countStep];
}
- (IBAction)segmentValueChange:(id)sender {
[self updateStepUI];
}
#pragma mark - Functions Private
- (void)countStep
{
// if (self.isRequesting == YES) {
// return;
// }
if ([CMMotionActivityManager isActivityAvailable]) {
[progressHud showAnimated:YES];
[progressHud setHidden:NO];
// self.isRequesting = YES;
self.bike = 0;
self.walking = 0;
self.running = 0;
NSDate *startDate = [self.dateCurrent beginningAtMidnightOfDay];
NSDate *endDate = [startDate dateByAddingTimeInterval:(24*60*60 - 1)];
HomeViewController __weak *weakSelf = self;
dispatch_queue_t myQueue = dispatch_queue_create("mobileworld.jp.lifelog", NULL);
dispatch_async(myQueue, ^{
if (weakSelf == nil) {
return ;
}
[weakSelf.motionActivityManager queryActivityStartingFromDate:startDate toDate:endDate toQueue:_operationQueue withHandler:^(NSArray<CMMotionActivity *> * _Nullable activities, NSError * _Nullable error) {
if (error || activities.count <= 0) {
weakSelf.totalRequest = 0;
weakSelf.countComplete = 0;
dispatch_async(dispatch_get_main_queue(), ^{
[weakSelf updateStepUI];
});
return ;
}
// set EndDate
weakSelf.totalRequest = (int)activities.count;
NSMutableArray *arrayActivities = [[NSMutableArray alloc] init];
for (int i = 0; i < activities.count; i++) {
CMMotionActivity *activity = [activities objectAtIndex:i];
CMMotionActivityExtra *activityExtra = [[CMMotionActivityExtra alloc] init];
activityExtra.activity = activity;
if (i == activities.count - 1) {
activityExtra.endDate = endDate;
}
else {
CMMotionActivity *activityNext = [activities objectAtIndex:i+1];
activityExtra.endDate = activityNext.startDate;
}
[arrayActivities addObject:activityExtra];
}
for (CMMotionActivityExtra *activityExtra in arrayActivities) {
// NSLog(@"%@", activityExtra.activity.startDate);
[weakSelf.pedometer queryPedometerDataFromDate:activityExtra.activity.startDate toDate:activityExtra.endDate withHandler:^(CMPedometerData * _Nullable pedometerData, NSError * _Nullable error) {
NSInteger numberStep = [pedometerData.numberOfSteps integerValue];
int mode = 1;
if (activityExtra.activity.cycling) {
// self.bike
weakSelf.bike += numberStep;
//NSLog(@"Step cycling");
mode = 3;
}
else if (activityExtra.activity.walking) {
// self.walking
weakSelf.walking += numberStep;
//NSLog(@"Step walking");
mode = 1;
}
else if (activityExtra.activity.running) {
weakSelf.running += numberStep;
//NSLog(@"Step running");
mode = 2;
}
else {
// unknown
//NSLog(@"Step unknown");
}
// NSLog(@"Number of step--> %ld", numberStep);
weakSelf.countComplete += 1;
// save step to server
if (numberStep > 0) {
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSString *dateBegin = [dateFormatter stringFromDate:activityExtra.activity.startDate];
NSString *dateEnd = [dateFormatter stringFromDate:activityExtra.endDate];
[[ServerAPI server] requestCreateLog:mode withStep:(int)numberStep startDate:dateBegin endDate:dateEnd CompletionHandler:^(NSError *error) {
if (error) {
NSLog(@"Error: %@", error);
}
}];
}
dispatch_async(dispatch_get_main_queue(), ^{
[weakSelf updateStepUI];
});
}];
}
// NSLog(@"-----------------------------------------------------");
}];
});
}
else {
[progressHud setHidden:YES];
}
}
- (void)updateStepUI //:(NSInteger)numberStep
{
if (self.totalRequest == self.countComplete) {
switch (self.segmentHome.selectedSegmentIndex) {
case 0:
self.lblValueStep.text = [Utilities addCommaFromNumber:self.bike];
self.lblValueStepOther.text = [NSString stringWithFormat:@"%@ %ld", NSLocalizedString(@"lifelog.today.remaining.other", nil), numberTotal - self.bike];
self.lblPercent.text = [NSString stringWithFormat:@"%@ %i%@", NSLocalizedString(@"lifelog.today.text.percent", nil), (int)(self.bike*100/numberTotal), NSLocalizedString(@"lifelog.today.percent", nil)];
break;
case 1:
self.lblValueStep.text = [Utilities addCommaFromNumber:self.walking];
self.lblValueStepOther.text = [NSString stringWithFormat:@"%@ %ld", NSLocalizedString(@"lifelog.today.remaining.other", nil), numberTotal - self.walking];
self.lblPercent.text = [NSString stringWithFormat:@"%@ %i%@", NSLocalizedString(@"lifelog.today.text.percent", nil), (int)(self.walking*100/numberTotal), NSLocalizedString(@"lifelog.today.percent", nil)];
break;
case 2:
self.lblValueStep.text = [Utilities addCommaFromNumber:self.running];
self.lblValueStepOther.text = [NSString stringWithFormat:@"%@ %ld", NSLocalizedString(@"lifelog.today.remaining.other", nil), numberTotal - self.running];
self.lblPercent.text = [NSString stringWithFormat:@"%@ %i%@", NSLocalizedString(@"lifelog.today.text.percent", nil), (int)(self.running*100/numberTotal), NSLocalizedString(@"lifelog.today.percent", nil)];
break;
default:
break;
}
// NSLog(@"Walking: %ld || Running: %ld || Bike: %ld", self.walking, self.running, self.bike);
// self.isRequesting = NO;
self.countComplete = 0;
self.totalRequest = 0;
[progressHud setHidden:YES];
}
}
@end