使用CoreMotion框架在后台接收加速度计更新

我正在使用下面的代码来获取加速计数据(使用CoreMotion框架):

 CMMotionManager *motionManager = [[CMMotionManager alloc] init]; motionManager.accelerometerUpdateInterval = 1.0 / 60.0; [motionManager startAccelerometerUpdatesToQueue:[NSOperationQueue currentQueue] withHandler:^(CMAccelerometerData *accelerometerData, NSError *error) { NSLog(@"ACCELEROMETER DATA = %@",accelerometerData); }]; 

当应用程序处于前景模式时,我正在接收日志,但是当它进入后台时,只有当应用程序中的音乐正在播放时才会收到日志。 我已经将以下内容添加到应用程序信息plist文件中:

 - Required background modes - App registers for location updates - App plays audio or streams audio/video using AirPlay 

问题是:当音乐不播放时,如何在后台接收加速度计更新?

您不仅可以使用加速计从后台获取数据,

正如你所说的你的App registers for location updates ,在前台启动位置pipe理器。

实施长期运行的后台任务

对于需要更多执行时间来执行的任务,您必须请求特定的权限才能在后台运行它们,而不会被暂停。 在iOS中,只有特定的应用程序types才能在后台运行:

  1. 在后台播放可听内容的应用,例如音乐播放器应用
  2. 在后台录制audio内容的应用程序。
  3. 随时向用户通知其位置的应用,例如导航应用
  4. 支持网际协议语音(VoIP)的应用
  5. 需要定期下载和处理新内容的应用程序
  6. 从外部附件获得定期更新的应用程序

在你的AppDelegate.m

 - (void)applicationDidEnterBackground:(UIApplication *)application { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. UIApplication* app = [UIApplication sharedApplication]; __block UIBackgroundTaskIdentifier bgTask = [app beginBackgroundTaskWithExpirationHandler:^{ [app endBackgroundTask:bgTask]; bgTask = UIBackgroundTaskInvalid; }]; }