在没有使用GCD时,当app被按home键退出后,app仅有最多5秒钟的时候做一些保存或清理资源的工作。但是在使用GCD后,app最多有10分钟的时间在后台长久运行。这个时间可以用来做清理本地缓存,发送统计数据等工作。
Declaration
SWIFT
typealias UIBackgroundTaskIdentifier = Int
OBJECTIVE-C
typedef NSUInteger UIBackgroundTaskIdentifier;
Import Statement
OBJECTIVE-C
@import UIKit;
SWIFT
import UIKit
Availability
Available in iOS 4.0 and later.
代码例子:
- (void)applicationDidEnterBackground:(UIApplication *)application {
__block UIBackgroundTaskIdentifier bgTask;
bgTask = [application beginBackgroundTaskWithExpirationHandler:^{
dispatch_async(dispatch_get_main_queue(), ^{
if (bgTask != UIBackgroundTaskInvalid)
{
bgTask = UIBackgroundTaskInvalid;
}
});
}];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"555555");
});
});
}
代码例子:
后台播放音乐
+ (UIBackgroundTaskIdentifier)backgroundPlayerID:(UIBackgroundTaskIdentifier)backTaskId
{
// 1. 设置并激活音频会话类别
AVAudioSession *session = [AVAudioSession sharedInstance];
[session AVAudioSessionCategoryPlayback error:nil];
[session setActive:YES error:nil];
// 2. 允许应用程序接收远程控制
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
// 3. 设置后台任务ID
UIBackgroundTaskIdentifier newTaskId = UIBackgroundTaskInvalid;
newTaskId = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:nil];
if (newTaskId != UIBackgroundTaskInvalid && backTaskId != UIBackgroundTaskInvalid) {
[[UIApplication sharedApplication] endBackgroundTask:backTaskId];
}
return newTaskId;
}