iOS 7或更高版本中的默认后台获取时间间隔为3 min
,但我希望在2 hours
之后进行后台获取以进行新闻更新。
我尝试了很多方法,比如ie。
NSTimer
Sleep
主题background fetch internal
经过艰苦的努力,结果是
crash
foreground
然后新闻更新no new data update
我试过这段代码:
- (void)applicationDidEnterBackground:(UIApplication *)application
{
__block UIBackgroundTaskIdentifier taskID=[[UIApplication sharedApplication]beginBackgroundTaskWithExpirationHandler:^{
NSLog(@"background task expiration handler called");
NSLog(@"Task ID is:%lu",(unsigned long)taskID);
[[UIApplication sharedApplication]endBackgroundTask:taskID];
}];
if(taskID==UIBackgroundTaskInvalid)
{
NSLog(@"Failed to start background task");
return;
}
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSLog(@"Start Background task with %f seconds remaining",[[UIApplication sharedApplication]backgroundTimeRemaining ]);
[self download];
[NSThread sleepForTimeInterval:25];
NSLog(@"Finishing Background task with %f seconds remaining",[[UIApplication sharedApplication]backgroundTimeRemaining ]);
[[UIApplication sharedApplication]endBackgroundTask:taskID];
});
}
-(void)download
{
ViewController *viewController = (ViewController *)self.window.rootViewController;
NSDate *fetchStart=[NSDate date];
[viewController fetchNewDataWithCompletionHandler:^(UIBackgroundFetchResult result) {
viewController.i++;
if(viewController.i<5)
{
[self download];
}
NSLog(@"%lu",(unsigned long)result);
}];
NSDate *fetchEnd = [NSDate date];
NSTimeInterval timeElapsed = [fetchEnd timeIntervalSinceDate:fetchStart];
NSLog(@"Background Fetch Duration: %f seconds", timeElapsed);
}
我使用
recursion
更新了五个新闻频道。我的设备没有 已连接到X-Code
。我的后台获取功能已启用。