在后台运行应用程序超过10分钟

我试图保持iOS应用程序进入后台状态超过10分钟的活动状态。

我怎样才能实现这一点。

请参阅iPhoneAppProgrammingGuide的 “后台执行”部分。 总之,你的应用程序必须是以下types之一:

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

您必须按以下方式添加到Info.plist中:将UIBackgroundModes项添加到Info.plist文件中,并将其值设置为包含一个或多个以下string的数组:

  • audio – 应用程序在后台播放可听内容给用户。 (此内容包括使用AirPlay播放audio或video内容。)
  • 位置 – 即使在后台运行时,应用程序也能让用户了解自己的位置。
  • voip-该应用程序提供用户使用Internet连接拨打电话的function。
  • 报亭内容 – 该应用程序是一个新闻报道应用程序,在后台下载和处理杂志或报纸内容。
  • 外部附件 – 该应用程序与需要通过外部附件框架定期传递更新的硬件附件配合使用。
  • 蓝牙中央 – 该应用程序与蓝牙配件,需要通过CoreBluetooth框架定期提供更新

请注意,审查过程的一部分将进行检查,以确保您的应用程序做它所做的背景处理。

这是我用beginBackgroundTaskWithExpirationHandler完成的。

  • 编写一个启动后台任务的方法。
  • 在该后台任务中,运行一个NSTimer ,计划(不重复)的时间在10分钟以内。 为了我的情况,我使用了5分钟。
  • 一旦NStimer的select器激活,结束后台任务,然后立即调用您之前编写的方法来启动另一个后台任务。
  • 如果你想安排在特定时间运行的方法,你将不得不在后台任务中检查它们。

这个解决scheme并不是非常理想,仍然是电力饥饿,但会做你想做的事情。

编辑:自iOS7以来,我build议你读这个优秀的职位 。

只有某些types的应用程序被允许在后台运行。 请参阅本指南的“实施长时间运行的后台任务”一节。

如果您没有请求执行后台处理的权限,则可以使用UIApplication的beginBackgroundTaskWithExpirationHandler,但无法获得额外的时间。

这段代码让你的iOS应用程序在后台无限期运行。 将下面的方法复制并粘贴到单例/pipe理器中,以处理需要在后台执行的任务。

 // @interface // Declare Private property @property (nonatomic) UIBackgroundTaskIdentifier backgroundTask; //@end // ... // Copy into //@implementation - (void)setupBackgrounding { [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(appBackgrounding:) name: UIApplicationDidEnterBackgroundNotification object: nil]; [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(appForegrounding:) name: UIApplicationWillEnterForegroundNotification object: nil]; } - (void)appBackgrounding: (NSNotification *)notification { [self keepAlive]; } - (void) keepAlive { self.backgroundTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{ [[UIApplication sharedApplication] endBackgroundTask:self.backgroundTask]; self.backgroundTask = UIBackgroundTaskInvalid; [self keepAlive]; }]; } - (void)appForegrounding: (NSNotification *)notification { if (self.backgroundTask != UIBackgroundTaskInvalid) { [[UIApplication sharedApplication] endBackgroundTask:self.backgroundTask]; self.backgroundTask = UIBackgroundTaskInvalid; } } 

你不能。 除非你的应用程序使用audio,VoIP或GPS。 你可以做的是通知用户(通过本地通知)时间快到了,并要求他打开/closures应用程序。

另外,如果您只需要通知用户,则可以使用推送通知。

https://github.com/yarodevuci/backgroundTask在这里检查我的代码我正在使用播放空白的WAV文件的audio播放器在IOS 8完美工作24小时内电池使用率约10%如何使用:

 var backgroundTask = BackgroundTask() backgroundTask.startBackgroundTask() //Starts playing blank audio file. You can run NSTimer() or whatever you need and it will continue executing in the background. backgroundTask.stopBackgroundTask() //Stops the task 

警告:如果您尝试提交,苹果公司会拒绝这个!