启动后台运行任务时,调用UIApplication的实例方法beginBackgroundTaskWithExpirationHandler:
任务完成后,调用UIApplication实例方法endBackgroundTask:
//AppDelegate.h
#import <UIKit/UIKit.h>
@interface AppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
@property (nonatomic, unsafe_unretained) UIBackgroundTaskIdentifier backgroundIdentifier;
@property (nonatomic, strong) NSTimer *myTimer;
@end
// AppDelegate.m
// test
//
#import "AppDelegate.h"
@implementation AppDelegate
@synthesize window;
@synthesize backgroundIdentifier;
@synthesize myTimer;
// 首先判断设备是否支持多任务
- (BOOL)isMultitaskingSupported
{
BOOL result = NO;
if ([[UIDevice currentDevice] respondsToSelector:@selector(isMultitaskingSupported)]) {
result = [[UIDevice currentDevice] isMultitaskingSupported];
}
return result;
}
- (void)timerMethod:(NSTimer *)paramSender{
//获取后台任务可执行时间,单位秒,若应用未能在此时间内完成任务,则应用将被终止
NSTimeInterval backgroundTimeRemaining = [[UIApplication sharedApplication] backgroundTimeRemaining];
//应用处于前台时,backgroundTimeRemaining值为DBL_MAX
if (backgroundTimeRemaining == DBL_MAX) {
NSLog(@"Background time remaining = Undetermined");
} else {
NSLog(@"Background time remaining = %.02f seconds", backgroundTimeRemaining);
}
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
if ([self isMultitaskingSupported]) {
NSLog(@"Multitasking is supported.");
} else {
NSLog(@"Multitasking is not supported.");
}
return YES;
}
//进入后开启任务
- (void)applicationDidEnterBackground:(UIApplication *)application
{
if ([self isMultitaskingSupported] == NO){
return; }
self.myTimer =
[NSTimer scheduledTimerWithTimeInterval:1.0f
target:self
selector:@selector(timerMethod:) userInfo:nil
repeats:YES];
self.backgroundIdentifier = [application beginBackgroundTaskWithExpirationHandler:^(void) {
[self endBackgroundTask];
}];
}
- (void) endBackgroundTask{
dispatch_queue_t mainQueue = dispatch_get_main_queue();
__weak AppDelegate *weakSelf = self;
dispatch_async(mainQueue, ^(void) {
AppDelegate *strongSelf = weakSelf;
if (strongSelf != nil){
[strongSelf.myTimer invalidate];
[[UIApplication sharedApplication] endBackgroundTask:self.backgroundIdentifier];
strongSelf.backgroundIdentifier = UIBackgroundTaskInvalid;
}
});
}
@end