简体   繁体   English

如何在iOS中使用后台模式BLE Central添加后台无限计时器?

[英]How to add background infinite timer with background mode BLE Central in IOS?

I want to keep my app can fire timer at specific time even when in background,now my app use BLE Central background mode, and I need to send some data to blue peripheral at a specific time, how to implement this? 我想让我的应用程序即使在后台也可以在特定时间触发计时器,现在我的应用程序使用BLE Central后台模式,并且我需要在特定时间向蓝色外围设备发送一些数据,如何实现呢? Now the timer selector seems can only be fired when enter back to foreground. 现在,计时器选择器似乎只能在输入回到前台时才能被触发。 I use Xcode 6.3, tested both on iOS 8.1.3 and iOS 8.3. 我使用在iOS 8.1.3和iOS 8.3上均经过测试的Xcode 6.3。

To allow to work your timer in background mode, you need to enable Uses Bluetooth LE accessories flag ON (Path : Go to target --> capabilities --> Background Modes). 要使您的计时器在background模式下工作,您需要启用“ Uses Bluetooth LE accessories标记为ON (路径:转到目标->功能->后台模式)。 like as below. 如下所示。

在此处输入图片说明

And add following code in your project to run timer in background : 并在您的项目中添加以下代码以在background运行计时器:

Step 1: Declare __block UIBackgroundTaskIdentifier bgTask as global variable. 步骤1:将__block UIBackgroundTaskIdentifier bgTask声明为全局变量。

Step 2: To add following code in applicationDidEnterBackground. 步骤2:在applicationDidEnterBackground中添加以下代码。

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


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

}

Step 3: Stop background task handler once apps come in foreground mode. 步骤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];


}

But the timer selector seems can only be fired when app become foreground again. 但是计时器选择器似乎只能在应用再次成为前台时被触发。 Should I use dispatch_after instead of nstimer?But the dispatch_after can not be canceled once it is scheduled. 我应该使用dispatch_after而不是nstimer吗?但是一旦调度,就不能取消dispatch_after。

I have the problem with my existing application. 我的现有应用程序有问题。 iOS not allow to run the timer in background even if you have enable the background mode for BLE. 即使您启用了BLE的后台模式,iOS也不允许在后台运行计时器。 It allow only for “Airplay, Airdrop, Picture in Picture” background mode. 它仅支持“ Airplay,Airdrop,画中画”背景模式。 BLE background mode only used for to make it continue connection. BLE后台模式仅用于使其继续连接。 But in iOS v12.0 BLE disconnection event not trigger if your app have in background around 2 to 3 hrs. 但是在iOS v12.0中,如果您的应用在后台运行2到3个小时左右,则不会触发BLE断开事件。 But it perfectly working fine on older versions. 但是在旧版本上可以正常工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM