我知道的主要目的是
-(void)locationManager:(CLLocationManager*)manager
didRangeBeacons:(NSArray*)beacons
inRegion:(CLBeaconRegion*)region
是在应用程序处于前台时工作。
在后台时,
- (void)locationManager:(CLLocationManager*)manager didEnterRegion:(CLRegion *)region
用于检测信标,但没有所需的信息(来自 CLBeacons 的次要和主要 ID 以提供上下文信息)。
我知道 CLLocationManager 的委托(delegate)方法允许在后台短暂运行代码。
是否可以这样做: - 进入一个区域时在背景中短暂地开始测距信标 - 根据次要/主要 ID 在后台调用 Web 服务 - 发送配置了 web 服务返回结果的 UILocalNotification
- (void)locationManager:(CLLocationManager*)manager didEnterRegion:(CLRegion *)region
{
if (![region isKindOfClass:[CLBeaconRegion class]]) return;
[locationManager startRangingBeaconsInRegion:(CLBeaconRegion*)region];
}
然后:
-(void)locationManager:(CLLocationManager*)manager
didRangeBeacons:(NSArray*)beacons
inRegion:(CLBeaconRegion*)region
{
if (beacons.count == 0) return;
CLBeacon *foundBeacon = [sortedBeacons firstObject];
// DO STUFF IN BACKGROUND
if ([[UIApplication sharedApplication] applicationState] != UIApplicationStateActive){
//Call for a webservice according to minor /major
//Dispatch contextual notification
// ^success(...)
UILocalNotification * theNotification = [[UILocalNotification alloc] init];
theNotification.alertBody = [NSString stringWithFormat:@""];
theNotification.fireDate = [NSDate dateWithTimeIntervalSinceNow:1];
[[UIApplication sharedApplication] scheduleLocalNotification:theNotification];
}
else{ //DO STUFF IN FOREGROUND
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"proximity"
ascending:YES];
NSSortDescriptor *sortDescriptor2 = [[NSSortDescriptor alloc] initWithKey:@"accuracy"
ascending:YES];
NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor,sortDescriptor2];
NSArray *sortedBeacons = [beacons sortedArrayUsingDescriptors:sortDescriptors];
//determine which beacon will be used to trigger foreground event
}
}
最佳答案
我经历过完全相同的场景。 我使用了以下模式:
// start background task
- (void)beginBackgroundTask {
if (self.backgroundTask != UIBackgroundTaskInvalid) {
[self endBackgroundTask];
}
self.backgroundTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
[self endBackgroundTask];
}];
}
// end background task
- (void)endBackgroundTask {
if (self.backgroundTask != UIBackgroundTaskInvalid) {
[[UIApplication sharedApplication] endBackgroundTask:self.backgroundTask];
}
self.backgroundTask = UIBackgroundTaskInvalid;
}
这些是我用来标记/取消标记调用网络服务等后台任务的常规方法。
以下是这些的一些使用模式:
[self beginBackgroundTask];
[[MySessionManager sharedInstance] POST:MoteList parameters:params success:^(NSURLSessionDataTask *task, id responseObject) {
// process the response
[self endBackgroundTask];
} failure:^(NSURLSessionDataTask *task, NSError *error) {
// error handling
}];
对了,这个后台任务时间段限制在3分钟左右。
还有另一个选项可以无限期地执行后台任务: 那就是使用 NSURLSession 从 iOS 7 开始支持的多任务 API。 但它只能用于下载/上传任务。 如果需要做 POST 请求,服务器响应应该是可下载的 json/xml 数据。 应用应将其下载到文件中并以编程方式解析。
希望对您有所帮助。
关于ios - 在后台测距 iOS 信标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21188011/