当应用程序不存在时监听信标 运行

Listening For Beacons When App is Not Running

当我的应用程序不是 运行 时,我正在尝试监听 iBeacons(用户退出应用程序并且它不是 运行 在后台)。

我已指定蓝牙 LE 后台模式,当应用程序处于活动状态并在后台时,我可以收听和接收目击事件。但是,当我的应用不是 运行.

时,我很难弄清楚如何实现相同的功能。

我一直在阅读 Core Bluetooth 指南并尝试实施 CBCentralManagerDelegate - 如果这是此场景的正确解决方案。我不明白我在哪里实施 CBCentralManagerDelegate。我是在 AppDelegate 中还是在处理信标目击事件的视图控制器中实现它?我必须声明 CBCentralManager 吗?我在 centralManagerDidUpdateState: 做什么?

我不关心恢复或保存状态,我只希望我的应用程序在不 运行 时接收信标目击。

我已经添加了 NSLocationAlwaysUsageDescription 并正在请求该位置的权限。

如果我可以提供更多信息,请告诉我。

Apple 对待 iBeacon 支持的方式不同于其他 BLE 服务。

它将 iBeacons 监控视为位置管理器服务。

您想将 NSLocationAlwaysUsageDescription 键添加到您应用的 info.plist。

在启动时,您想检查位置管理器的授权状态,如果不是kCLAuthorizationStatusAuthorizedAlways,那么您想请求它。该代码如下所示:

CLAuthorizationStatus status =[CLLocationManager authorizationStatus];

if (status != kCLAuthorizationStatusAuthorizedAlways
  && [self.theLocManager respondsToSelector: 
    @selector(requestAlwaysAuthorization)])
  {
    [self.theLocManager requestAlwaysAuthorization];
  }

编辑:

在您的应用委托的 application:didFinishLaunchingWithOptions: 方法中,您需要检查键 UIApplicationLaunchOptionsLocationKey 的选项。

引用CLLocationManager的相关部分Class参考:

If a region boundary crossing occurs while your iOS app is not running, the system automatically wakes it up (or relaunches it) in the background so that it can process the event. In this case, the options dictionary passed to the application:didFinishLaunchingWithOptions: method of your app delegate contains the key UIApplicationLaunchOptionsLocationKey to indicate that your app was launched because of a location-related event. During the relaunch process, you must recreate your location manager object and assign a delegate capable of handling region-related events. After you do that, the system delivers the region notification for which your app was launched. All of the regions you configured previously are made available in the monitoredRegions property of any location manager objects you create.