使用
1,申请后台权限
勾选后,会自动在app的info.plist文件中添加Required background modes一项,包含了所勾选的后台运行模式。如下所示:<key>UIBackgroundModes</key> <array> <string>fetch</string> </array>
2,设置获取时间间隔
在
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
方法中设置时间间隔-(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { [[UIApplication sharedApplication] setMinimumBackgroundFetchInterval:UIApplicationBackgroundFetchIntervalMinimum]; return YES; }
如果不对最小后台获取间隔进行设定的话,系统将使用默值UIApplicationBackgroundFetchIntervalNever,也就是永远不进行后台获取。而最小的时间间隔则有系统根据电量、网络状态、用户使用习惯等综合考量后来设定一定的差值,执行fetch任务
3,fetch任务
在
- (void)application:(UIApplication *)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
中执行任务-(void)application:(UIApplication *)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler{ // 刷新数据 completionHandler(UIBackgroundFetchResultNewData); }
completionHandler
回调返回状态typedef NS_ENUM(NSUInteger, UIBackgroundFetchResult) { UIBackgroundFetchResultNewData, UIBackgroundFetchResultNoData, UIBackgroundFetchResultFailed } NS_ENUM_AVAILABLE_IOS(7_0);
查看是否开启 Background Fetch 功能
[UIApplication sharedApplication].backgroundRefreshStatus
typedef NS_ENUM(NSInteger, UIBackgroundRefreshStatus) {
UIBackgroundRefreshStatusRestricted, //< unavailable on this system due to device configuration; the user cannot enable the feature
UIBackgroundRefreshStatusDenied, //< explicitly disabled by the user for this application
UIBackgroundRefreshStatusAvailable //< enabled for this application
} API_AVAILABLE(ios(7.0), tvos(11.0));
如何测试 Background Fetch 功能
在实际的IOS7环境中,Fetch事件是由系统管理的,app开发者无法预先知道Fetch事件达到的时机。
但XCode也提供了Fetch事件的调试办法,在XCode上运行程序后,在Debug->Simulate Background Fetch.
还有一种情况是app没有运行(不在前台也不在后台),被Fetch事件唤醒执行.这种情况的测试方法如下:
Product->Scheme->Edit scheme 在Debug模式选中Options,点选Launch due to a background fetch event,运行即可