我想知道如果CMMotionActivity发生变化,系统是否可以在后台唤醒应用程序,例如,如果用户在坐下后开始步行/跑步,我希望能够执行一些代码并安排本地通知.
有没有办法要求系统在后台唤醒我的应用程序?
编辑:通过查看reference,它似乎不可能(“[…]并且在您的应用程序被暂停时未提供更新.”),但也许还有另一种方式?
解决方法
我解决了这个问题,创建了一个后台计时器,并在名为method的选择器中检查活动类型.只需查看代码,以防它对您有用.我接受有关此的建议,更正和建议.
#define k_timer_time 10.0f @property NSTimer *timer; - (void) createBackGroundTimertocheckMotion{ // create new uibackgroundtask __block uibackgroundtaskIdentifier bgTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{ [[UIApplication sharedApplication] endBackgroundTask:bgTask]; bgTask = uibackgroundtaskInvalid; }]; __weak __typeof(self) weakSelf = self; // and create new timer with async call: dispatch_async(dispatch_get_global_queue(disPATCH_QUEUE_PRIORITY_DEFAULT,0),^{ weakSelf.timer = [NSTimer scheduledTimerWithTimeInterval:k_timer_time target:self selector:@selector(onTick:) userInfo:nil repeats:YES]; weakSelf.timer.tolerance = 5; [[NSRunLoop currentRunLoop] addTimer:weakSelf.timer forMode:NSDefaultRunLoopMode]; [[NSRunLoop currentRunLoop] run]; });
}
- (void) onTick:(NStimer*)timer{ if([CMMotionActivityManager isActivityAvailable]) { __weak __typeof(self) weakSelf = self; CMMotionActivityManager *cm = [[CMMotionActivityManager alloc] init]; CMpedometer *sc = [[CMpedometer alloc] init]; NSDate *Now = [NSDate date]; NSDate *last30Sec = [Now dateByAddingTimeInterval:-30]; [cm queryActivityStartingFromDate:last30Sec toDate:Now toQueue:[NSOperationQueue mainQueue] withHandler:^(NSArray *activities,NSError *error) { [activities enumerateObjectsUsingBlock:^(CMMotionActivity *a,NSUInteger idx,BOOL * _Nonnull stop) { //Your stuff here }]; }]; } else { NSLog(@"Error accessing Motion data"); }
}