在iOS中以后台模式将数据从中央传输到外围设备

时间:2015-02-26 10:51:37

标签: ios iphone xcode bluetooth-lowenergy background-process

我正在开发一个通过BLE进行自定义可穿戴设备的应用程序。

我已经在info.plist文件中订阅了用于Bluetooth-central的UI后台模式。 我通过分成每个200字节的块大小来传输大约600 kb的固件文件。这个过程很顺利但是当我按下主页按钮时,应用程序进入后台状态,从而在1-2分钟后终止进程。

如果我的屏幕在一定时间后变暗,则固件传输会继续,但只要按下主页按钮,应用就会在几分钟后停止传输数据。

请帮助我摆脱这种情况。

感谢。

1 个答案:

答案 0 :(得分:2)

要在后台模式下运行任务,您需要按照以下步骤操作。

步骤1:将__block UIBackgroundTaskIdentifier bgTask声明为全局变量。

第2步:在applicationDidEnterBackground中添加以下代码。

- (void)applicationDidEnterBackground:(UIApplication *)application {

    bgTask = [application beginBackgroundTaskWithExpirationHandler:^{
    bgTask = UIBackgroundTaskInvalid;
}];

}

步骤3:一旦应用程序进入前台模式,就停止后台任务处理程序。

- (void)applicationWillEnterForeground:(UIApplication *)application {
      // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.

      [[UIApplication sharedApplication] endBackgroundTask:bgTask];

}