锁定屏幕时,iOS停止查找信标

时间:2015-08-05 06:13:55

标签: ios objective-c iphone cllocationmanager ibeacon

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

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

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

  

告诉代表一个或多个信标在范围内。

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

enter image description here

这是我的测距信标代码:

- (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]; 
}

但只有遇到新的灯塔才会调用此方法。当我的应用程序处于前台时,我已经模拟了信标,所以当我用电源按钮调暗屏幕时,范围被停止并且监控从未被调用 - 我将不得不关闭/打开信标或走出/进入信标范围再次调用此方法。

1 个答案:

答案 0 :(得分:3)

iOS上的Beacon 范围通常仅在前台工作,并且在您的应用首次移至后台后约10秒。另一方面,Beacon 监控可以在后台运行,并在检测到信标时唤醒您的应用。如果您同时进行测距和监控,则在监控触发器在后台唤醒您的应用后,您将再次获得10秒的背景范围。

您可以根据要求将背景范围从10秒扩展到3分钟。我在how to do this上写了一篇博文。