iOS 锁定屏幕时停止寻找信标

iOS stops finding beacons when locking the screen

我编写了一个使用信标的应用程序,当该应用程序位于前台时一切正常。但是,当我按下电源按钮并调暗屏幕时,应用程序不再发现任何信标。该应用程序仍在点击:

- (void)locationManager:(CLLocationManager *)manager didRangeBeacons:(NSArray *)clBeacons inRegion:(CLBeaconRegion *)region

方法,但是记录器告诉我找到了 0 个信标,这很奇怪,因为根据文档,只有在范围内有任何信标时才应调用此方法:

Tells the delegate that one or more beacons are in range.

我已经获得了用户的 kCLAuthorizationStatusAuthorizedAlways 许可(它也被添加到 .plist 文件中)并且我已经将这些功能添加到项目中:

这是我的测距信标代码:

- (instancetype)init {
    self = [super init];
    if (self) {
        NSUUID *proximityUUID = [[NSUUID alloc] initWithUUIDString:[Registry environment].config.beaconUuid];
        self.region = [[CLBeaconRegion alloc] initWithProximityUUID:proximityUUID identifier:proximityUUID.UUIDString];

        self.locationManager = [CLLocationManager new];
        self.locationManager.delegate = self;
    }
    return self; 
}

- (void)stopMonitoringBeacons {
    [self.locationManager stopMonitoringForRegion:self.region];
    DDLogInfo(@"Stopped monitoring beacons."); 
}

- (void)locationManager:(CLLocationManager *)manager didStartMonitoringForRegion:(CLRegion *)region {
    [manager requestStateForRegion:region];
    [self startRangingBeacons]; 
}

- (void)startRangingBeacons {
    [self.locationManager startRangingBeaconsInRegion:self.region];
    DDLogInfo(@"Started ranging beacons."); 
}

- (void)locationManager:(CLLocationManager *)manager rangingBeaconsDidFailForRegion:(CLBeaconRegion *)region withError:(NSError *)error {
    DDLogInfo(@"Beacon ranging failed with error: %@.", error.localizedDescription); 
}

- (void)locationManager:(CLLocationManager *)manager didRangeBeacons:(NSArray *)clBeacons inRegion:(CLBeaconRegion *)region {
    DDLogDebug(@"Found %tu beacons.", clBeacons.count); 

    // call the server (no worries, not all the time)
}

知道我错过了什么吗?或者我可能不相信这些日志?

已解决:

问题出在我测试它的方式上。正如@davidgyoung 提到的,测距只在前台工作,如果我们想在后台 运行 它,我们需要从监控开始,它会通知我们后台有新的信标。我已经在我的代码中做到了:

- (void)locationManager:(CLLocationManager *)manager didStartMonitoringForRegion:(CLRegion *)region {
    [manager requestStateForRegion:region];
    [self startRangingBeacons]; 
}

但是只有当我们遇到新的信标时才会调用这个方法。当我的应用程序处于前台时,我已经在模拟信标,所以当我使用电源按钮使屏幕变暗时,测距停止并且从未调用监控 - 我将不得不转动信标 off/on 或步行 out/in再次调用此方法的信标范围。

Beacon ranging on iOS 通常只在前台工作,并且在您的应用首次移至后台后持续约 10 秒。另一方面,Beacon monitoring 可以在后台工作并在检测到 beacon 时唤醒您的应用程序。如果您同时进行测距和监测,在监测触发器在后台唤醒您的应用程序后,您将再次获得 10 秒的背景测距。

您可以根据要求将背景时间延长 10 秒到 3 分钟。我在 how to do this 上写了一篇博客 post。