在我的应用程序中,我每分钟都会从服务器获取更新。对于后台,我正在使用代码
UIApplication* app = [UIApplication sharedApplication];
bti = [app beginBackgroundTaskWithExpirationHandler:^{
NSLog(@"Debug - Ending background task %d",bti);
[app endBackgroundTask:bti];
NSLog(@"Debug - Background task %d ended",bti);
bti = UIBackgroundTaskInvalid;
}];
NSLog(@"Debug - Starting background task %d",bti);
[NSTimer scheduledTimerWithTimeInterval:60.0 target: self
selector: @selector(anyTask) userInfo:nil repeats: YES];
但是应用程序在一段时间后终止并获取日志
{(
<BKProcessAssertion: 0x15ddbf50> identifier: Background Content Fetching (79) process: DemoApp[628] permittedBackgroundDuration: 30.000000 reason: backgroundContentFetching owner pid:33 preventSuspend preventThrottleDownUI preventIdleSleep preventSuspendOnSleep
)}
我还使用了这样的背景获取:
-(void)application:(UIApplication *)application
performFetchWithCompletionHandler:
(void (^)(UIBackgroundFetchResult))completionHandler {
NSLog(@"Background fetch started...");
[self repeatTask];
// //---do background fetch here---
NSLog(@"Background fetch completed...");
}
任何帮助,将不胜感激 :)
最佳答案
您不能使用此技术无限期地在后台运行。您可以使用后台获取模式来允许您的应用轮询服务器(但频率为分钟或几小时),也可以让服务器使用推送通知来提醒您的应用有新内容。您当前的方法对电池不太友好
如果要使用后台获取模式,则需要以适当的结果调用提供的completionHandler
-
completionHandler(UIBackgroundFetchResultNewData);
要么
completionHandler(UIBackgroundFetchResultNoData);
要么
completionHandler(UIBackgroundFetchResultFailed);
在
performFetchWithCompletionHandler:
的末尾例如
-(void)application:(UIApplication *)application
performFetchWithCompletionHandler:
(void (^)(UIBackgroundFetchResult))completionHandler {
NSLog(@"Background fetch started...");
if ([self repeatTask]) { // //---do background fetch here--- returns YES if new data
completionHandler(UIBackgroundFetchResultNewData);
}
else {
completionHandler(UIBackgroundFetchResultNoData);
}
NSLog(@"Background fetch completed...");
}
关于ios - 后台模式在iOS 8中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26231652/