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];
終止任務。程序會在後臺運行,但並非無限時間。