[英]Is there a way, in background, to get my app notified when the CMMotionActivity changes?
I'd like to know if the system can wake an application in the background if the CMMotionActivity changes, for example, if the user starts walking/running after sitting, I'd like to be able to execute some code and schedule a local notification. 我想知道如果CMMotionActivity发生变化,系统是否可以在后台唤醒应用程序,例如,如果用户在坐下后开始步行/跑步,我希望能够执行一些代码并安排本地通知。
Is there a way to ask the system to wake my app in the background for that ? 有没有办法要求系统在后台唤醒我的应用程序?
EDIT : By looking at the reference , it doesn't seem to be possible ("[...] and updates are not delivered while your app is suspended.") , but maybe is there an other way ? 编辑:通过查看引用 ,它似乎是不可能的(“[...]并且在您的应用程序被暂停时不会提供更新。”) , 但也许还有其他方法?
I solved this creating a background timer and checking for the activity type in the selector called method. 我解决了这个问题,创建了一个后台计时器,并在名为method的选择器中检查活动类型。 Just have a look to the code in case it can be useful for you.
只需查看代码,以防它对您有用。 I accept suggestions, corrections and advices over this.
我接受有关此的建议,更正和建议。
#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");
}
} }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.