iOS后台模式教程 (一)ios
原文服务器
在iOS7以前的系统中,当应用被挂起,拥有连续的10分钟时间来处理以前的任务,而后才会被系统终止。session
因此,后台模式有一些特殊的使用场景。例如,更新位置,播放视频音频,和更新服务器请求。app
第一步设置工程中的Capabilities
标签栏,打开Background Modes
服务。fetch
出现的Modes
选项有atom
Audio,AirPlay and Picture in Picture 视频音频播放code
Location updates 位置更新视频
Voice over IP IP电话教程
Newsstand downloads 杂志下载get
External accessory communication 外部附件通讯,包括App Watch
Uses Bluetooth LE accessories 蓝牙LE配件
Acts as a Bluetooth LE accessory 做为蓝牙LE配件
Background fetch 后台抓取服务
Remote notifications 远程通知
这里介绍几个模式的用法。
下面这段代码加入viewDidLoad中,程序开始时会按顺序播放两个mp3文件。在勾选Audio,AirPlay and Picture in Picture
后,挂起程序时,音乐仍是会继续播放 。
引用
#import <AVFoundation/AVFoundation.h>
参数
@property (nonatomic, strong) AVQueuePlayer *player;
viewDidLoad
NSError *sessionError = nil; [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayAndRecord error:&sessionError]; NSArray *queue = @[ [AVPlayerItem playerItemWithURL:[[NSBundle mainBundle] URLForResource:@"music" withExtension:@"mp3"]], [AVPlayerItem playerItemWithURL:[[NSBundle mainBundle] URLForResource:@"pop" withExtension:@"mp3"]]]; self.player = [[AVQueuePlayer alloc] initWithItems:queue]; self.player.actionAtItemEnd = AVPlayerActionAtItemEndAdvance; [self.player play];
参数
@property (nonatomic, strong) CLLocationManager *locationManager; @property (nonatomic, strong) NSMutableArray *locations;
初始化LocationManager
self.locations = [[NSMutableArray alloc] init]; self.locationManager = [[CLLocationManager alloc] init]; self.locationManager.desiredAccuracy = kCLLocationAccuracyBest; self.locationManager.delegate = self;
启动位置更新服务
[self.locationManager startUpdatingLocation];
记录新位置
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation { // Add another annotation to the map. if (UIApplication.sharedApplication.applicationState == UIApplicationStateActive) { //前台运行 else { //后台运行 NSLog(@"App is backgrounded. New location is %@", newLocation); } }
根据 UIApplication.sharedApplication.applicationState == UIApplicationStateActive
能够判断回调过程当中,程序是否挂起。记住要勾选Location updates
,当你在制做一个跑步或骑车软件时,须要用到这项功能。
这个宽泛的功能包括上传或者下载任务等。
@property (nonatomic) UIBackgroundTaskIdentifier backgroundTask;
self.backgroundTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{ // NSLog(@"Background handler called. Not running background tasks anymore."); [[UIApplication sharedApplication] endBackgroundTask:self.backgroundTask]; self.backgroundTask = UIBackgroundTaskInvalid; }];
您也能够在任务完成的时候,主动调用 [[UIApplication sharedApplication] endBackgroundTask:self.backgroundTask];
终止任务。程序会在后台运行,但并非无限时间。