当我们有需求,需要应用在后台长久的运行一段时间,此时,就需要用到方法
代码仅作记录和分享,详情参考唐巧的相关书籍。
在AppDelegate.h
@property (assign, nonatomic) UIBackgroundTaskIdentifier backgroundUpdateTask;
在AppDelegate.m
- (void)applicationDidEnterBackground:(UIApplication *)application {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
[self beginBackgroundUpdateTask];
//在这里加上需要长久运行的代码
[self endBackgroudUpdateTask];
}
- (void)beginBackgroundUpdateTask{
self.backgroundUpdateTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
[self endBackgroudUpdateTask];
}];
}
- (void)endBackgroudUpdateTask{
[[UIApplication sharedApplication] endBackgroundTask:self.backgroundUpdateTask];
self.backgroundUpdateTask = UIBackgroundTaskInvalid;
}
这样,可以保证应用在后台运行长达10min的时间
网友评论