循环在后台模式

时间:2016-02-29 18:10:12

标签: ios objective-c appdelegate

我想在后台搜索RSSI。我试图通过在同一个函数中调用函数来做到这一点。无论如何使这个循环生活在后台模式。正如我所看到的那样,它应该生活在背景中,但是我死后就死了。如何让它继续搜索?

- (void)applicationWillResignActive:(UIApplication *)application
{
    if([[UIDevice currentDevice] respondsToSelector:@selector(isMultitaskingSupported)])
    {
        NSLog(@"Multitasking Supported");
    }
    else
    {
        NSLog(@"Multitasking Not Supported");
    }

    NSLog(@"Start background task");
    mBeaconDeviceList = [[NSMutableArray alloc] init];
    mBeaconConfigManager = [[JLEBeaconConfigManager alloc] init];
    mBeaconConfigManager.delegate = self;
    [mBeaconConfigManager startJaaleeBeaconsDiscovery];
}

#pragma mark - JLEBeaconConfigManager delegate
-(void)beaconConfigManager:(JLEBeaconConfigManager *)manager didDiscoverBeacon:(JLEBeaconDevice *)beacon RSSI:(NSNumber *)RSSI AdvData:(NSDictionary *)AdvData
{
    NSLog(@"Find RSSI");
    if ([RSSI intValue] > 0 || [RSSI intValue] < -40) {
        return;
    }

    if ([mBeaconDeviceList containsObject:beacon]) {
        [mBeaconDeviceList removeObject:beacon];
    }
    [mBeaconDeviceList addObject:beacon];
    NSLog(@"FOUND: %@", RSSI);

    NSLog(@"Start again");
    mBeaconDeviceList = [[NSMutableArray alloc] init];
    mBeaconConfigManager.delegate = self;
    [mBeaconConfigManager startJaaleeBeaconsDiscovery];
}

1 个答案:

答案 0 :(得分:2)

您可以将后台时间延长至3分钟,这样您就可以有更多时间从RSSI进行搜索。您可以在applicationDidEnterBackground中扩展它,如下所示:

- (void)extendBackgroundRunningTime {
    if (_backgroundTask != UIBackgroundTaskInvalid) {
        // if we are in here, that means the background task is already running.
        // don't restart it.
        return;
    }
    NSLog(@"Attempting to extend background running time");

    __block Boolean self_terminate = YES;

    _backgroundTask = [[UIApplication sharedApplication] beginBackgroundTaskWithName:@"DummyTask" expirationHandler:^{
        NSLog(@"Background task expired by iOS");
        if (self_terminate) {
            [[UIApplication sharedApplication] endBackgroundTask:_backgroundTask];
            _backgroundTask = UIBackgroundTaskInvalid;
        }
    }];

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSLog(@"Background task started");

        while (true) {
            NSLog(@"background time remaining: %8.2f", [UIApplication sharedApplication].backgroundTimeRemaining);
            [NSThread sleepForTimeInterval:1];
        }

    });
}