从ios7 开始,苹果为了优化后台逻辑,新增了backgroundfetch这种模式。我们就来看看是怎么一回事吧!
要想让自己的app支持 backgroundfetch,需要在xcode 当中配置一下。在target->Capabilities->backgroundModes打开。勾选上backgroundfetch选项。
接下来,就是写代码了~~~ 为了保证后台获取尽可能多次的进行。
在
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
加上这句话
[[UIApplication sharedApplication] setMinimumBackgroundFetchInterval:UIApplicationBackgroundFetchIntervalMinimum];
然后我们需要实现一个委托函数,就是你需要在后台获取的时候做什么事情。
-(void)application:(UIApplication *)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
{
if ([UIApplication sharedApplication].backgroundRefreshStatus == UIBackgroundRefreshStatusAvailable)
{
LoadingViewController* vc = ((UINavigationController*)self.window.rootViewController).topViewController;
[vc updateImage];
completionHandler(UIBackgroundFetchResultNewData);
}
}
这里的updateImage 函数会去获取一个网络图片资源。然后更新界面。
最后别忘了调用
completionHandler(UIBackgroundFetchResultNewData);
否则界面不会在后台刷新。运行app 之后 home切换到后台,然后会不定时的获取内容。
如果你没有耐心的话,可以通过xcode 手动触发此场景 Debug->simulator BackgroundFetch