[英]Ranging beacons in background
我想在后台響起信標。 背景是指手機進入鎖屏狀態。 我希望該應用繼續跟蹤信標。 我現在遇到的問題是代碼永遠找不到信標。 我有兩個正在運行的信標,但AppDelegate找不到它們。 當我在ViewController中運行相同的代碼時,它會找到信標並顯示它們。 我該怎么做?
@interface BDAppDelegate () <AXABeaconManagerDelegate>
@end
@implementation BDAppDelegate {
NSMutableDictionary *beaconRegions;
NSMutableDictionary *detectBeacons;
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
return YES;
}
- (void)applicationWillResignActive:(UIApplication *)application {
}
- (void)applicationDidEnterBackground:(UIApplication *)application {
CLBeaconRegion *beaconRegion = [[CLBeaconRegion alloc] initWithProximityUUID:[[NSUUID alloc] initWithUUIDString:@"MyUUID"] identifier:@"微信"];
[AXABeaconManager sharedManager].beaconDelegate = self;
[[AXABeaconManager sharedManager] requestAlwaysAuthorization];
[[AXABeaconManager sharedManager] startRangingBeaconsInRegion:beaconRegion];
self->beaconRegions = [[NSMutableDictionary alloc] init];
self->detectBeacons = [[NSMutableDictionary alloc] init];
while (detectBeacons.count < 10) {
NSLog(@"Rows in detectBeacons %lu", (unsigned long)beaconRegions.count);
}
self->beaconRegions[beaconRegion] = [NSArray array];
}
- (void)didRangeBeacons:(NSArray *)beacons inRegion:(CLBeaconRegion *)region {
self->beaconRegions[region] = beacons;
NSMutableArray *allBeacons = [NSMutableArray array];
for (NSArray *regionResult in [self->beaconRegions allValues])
{
[allBeacons addObjectsFromArray:regionResult];
}
NSPredicate *pre = [NSPredicate predicateWithFormat:@"accuracy != -1"];
NSArray *rights = [allBeacons filteredArrayUsingPredicate:pre];
NSString * str = @"accuracy";
self->detectBeacons[str] = rights;
}
@end
在iOS上, 應用在后台的范圍限制為5秒 。 每次將應用置於后台時,或在觸發信標監視事件(進入區域/退出區域)時,都會重新啟動此計時器。 好消息是, 您可以將在每個這些事件之后,將后台范圍內的信標允許的時間延長到3分鍾。
我整理了一篇博客文章,向您展示如何做到這一點。
對於CLLocationManager,有一種方法startMonitoringForRegion(CLBeaconRegion *):beaconRegion
應該在開始startRangingBeaconsInRegion
之前添加startRangingBeaconsInRegion
。
因此,如果您的AXABeaconManager類來自CLLocationManager,請添加以下內容:
[[AXABeaconManager sharedManager] startMonitoringForRegion:beaconRegion];
否則:創建一個CLLocationManager對象locationManager並對其進行初始化,然后添加如下所示的啟動監視。
[self.locationManager startMonitoringForRegion:beaconRegion];
開始之前startRangingBeaconsInRegion
討論:startMonitoringForRegion必須為要監視的每個區域調用一次此方法。 如果應用已在監視具有相同標識符的現有區域,則舊區域將被新區域替換。 使用此方法添加的區域將由應用程序中的所有位置管理器對象共享,並存儲在monitoredRegions
屬性中。
更多信息請點擊這里
定位信標是一項消耗大量電池的操作,iOS不允許您在BG中無休止地進行操作(大多數情況下。在某些情況下,它可以工作)
您要做的就是將iOS稱為BG工作:
UIBackgroundTaskIdentifier token = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
NSLog(@"Ranging for region %@ killed", region.identifier);
}];
if(token == UIBackgroundTaskInvalid) {
NSLog(@"cant start background task");
}
然后做任何事
完成后,調用endBackgroundTask
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.