NSTimer *上的选择器是否可以在后台执行?

时间:2014-10-11 19:39:37

标签: ios background nstimer

具体来说,我正在查看后台应用程序收到位置服务更新(显着位置更改)的情况。在这种情况下,背景究竟发生了什么?任何用户代码都可以运行,包括挂起的计时器吗?

1 个答案:

答案 0 :(得分:0)

您可以使用后台任务和计时器,如下所示:

    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
    {
        // Override point for customization after application launch.
        self.locationManager = [[CLLocationManager alloc] init];
        self.locationManager.delegate = self;

        [self.locationManager startUpdatingLocation];
        return YES;
    }

- (void)applicationDidEnterBackground:(UIApplication *)application
{

    self.bgTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{


        [[UIApplication sharedApplication] endBackgroundTask:self.bgTask];
        self.bgTask = UIBackgroundTaskInvalid;
    }];


    self.timer = [NSTimer scheduledTimerWithTimeInterval:60
                                                  target:self
                                                selector:@selector(changeAccuracy)
                                                userInfo:nil
                                                 repeats:YES];
}


- (void) changeAccuracy {
    [self.locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
    [self.locationManager setDistanceFilter:kCLDistanceFilterNone];
}

-(void)locationManager:(CLLocationManager *)lm didUpdateLocations:(NSArray *)locations{
    CLLocation *location = [locations lastObject];

    NSLog(@"Location returned: %f, %f Accuracy: %f", location.coordinate.latitude, location.coordinate.longitude, location.horizontalAccuracy);
    [lm setDesiredAccuracy:kCLLocationAccuracyThreeKilometers];
    [lm setDistanceFilter:99999];
}