理想情况下,您永远不必检查该设置。看起来好像您正在以错误的方式绕过后台获取。随着应用程序最小化,系统将定期唤醒您的应用程序并允许其执行任务。从您的代码中,您想要更新位置。第一个开始的地方是这里,使用这个委托方法,当应用程序被唤醒以进行后台获取时,该方法会被调用
/// 具有“获取”后台模式的应用程序可能有机会在后台或系统方便时获取更新的内容。在这些情况下将调用此方法。您应该在执行完该操作后立即调用 fetchCompletionHandler,以便系统可以准确地估计其电量和数据成本。
- (void)application:(UIApplication *)application PerformFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult result))completionHandler NS_AVAILABLE_IOS(7_0);
这就是您使用它的方式,在您的应用程序委托实现中,定义方法体如下
-(void)application:(UIApplication *)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
{
NSLog(@"APP IS AWAKE FOR A BACKGROUND FETCH");
//do all the work you want to do
//once done, its important to call the completion hadler, otherwise the system will complain
completionHandler(UIBackgroundFetchResultNewData);
}
但是,由于您正在更新具有自己的委托的位置,因此您只希望在委托返回时而不是在此之前调用完成处理程序。调用完成处理程序将使您的应用程序返回睡眠状态。由于完成处理程序是一个块对象,因此它可以像任何其他对象一样传递。一种方法如下:在应用程序委托头文件中,定义一个块对象:
void (^fetchCompletionHandler)(UIBackgroundFetchResult);
然后在你的performFetchWithCompletionHandler中有:
-(void)application:(UIApplication *)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
{
fetchCompletionHandler = completionHandler;
NSLog(@"APP IS AWAKE FOR A BACKGROUND FETCH");
//do all the work you want to do
[self.locationManager startUpdatingLocation];
}
在某个适当的时间,在您的位置委托方法返回后,您可以调用
fetchCompletionHandler (UIBackgroundFetchResultNewData);
请务必检查您的 fetchCompletionHandler 是否为非 nil,当 nil 时调用它会立即使您的应用程序崩溃。在此处阅读 Apple 文档中有关块的更多信息https://developer.apple.com/library/ios/documentation/cocoa/conceptual/ProgrammingWithObjectiveC/WorkingwithBlocks/WorkingwithBlocks.html
还要看看调用 [[UIApplication sharedApplication] setMinimumBackgroundFetchInterval: ];它指定后台获取操作之间必须经过的最短时间。
您可能会将其放入应用程序委托应用程序的 didFinishLaunchingWithOptions 方法中。
希望这对您有帮助。