【发布时间】:2015-08-05 06:13:55
【问题描述】:
我编写了一个使用信标的应用程序,当应用程序在前台时一切正常。但是,当我按下电源按钮并使屏幕变暗时,应用程序不再找到任何信标。该应用仍在:
- (void)locationManager:(CLLocationManager *)manager didRangeBeacons:(NSArray *)clBeacons inRegion:(CLBeaconRegion *)region
方法,但是记录器告诉我找到了 0 个信标,这很奇怪,因为根据文档,只有在范围内有任何信标时才应该调用此方法:
告诉代理一个或多个信标在范围内。
我已经获得用户的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];
}
但是这个方法只有在遇到新的信标时才会被调用。当我的应用程序处于前台时,我已经在模拟信标,所以当我用电源按钮调暗屏幕时,测距停止并且从未调用过监控 - 我将不得不关闭/打开信标或走出/进入信标范围再次调用此方法。
【问题讨论】:
标签: ios objective-c iphone cllocationmanager ibeacon