這篇文章主要介紹了iOS怎樣實(shí)現(xiàn)后臺(tái)長(zhǎng)時(shí)間運(yùn)行,具有一定借鑒價(jià)值,感興趣的朋友可以參考下,希望大家閱讀完這篇文章之后大有收獲,下面讓小編帶著大家一起了解一下。
創(chuàng)新互聯(lián)建站專業(yè)為企業(yè)提供黎川網(wǎng)站建設(shè)、黎川做網(wǎng)站、黎川網(wǎng)站設(shè)計(jì)、黎川網(wǎng)站制作等企業(yè)網(wǎng)站建設(shè)、網(wǎng)頁(yè)設(shè)計(jì)與制作、黎川企業(yè)網(wǎng)站模板建站服務(wù),十載黎川做網(wǎng)站經(jīng)驗(yàn),不只是建網(wǎng)站,更提供有價(jià)值的思路和整體網(wǎng)絡(luò)服務(wù)。
前言
一般APP在按下Home鍵被掛起后,這時(shí)APP的 backgroundTimeRemaining 也就是后臺(tái)運(yùn)行時(shí)間大約只有3分鐘,如果在退出APP后,過(guò)十幾二十二分鐘或者更長(zhǎng)時(shí)間再回到APP,APP就會(huì)回到剛打開時(shí)的狀態(tài),也就是首頁(yè);有的項(xiàng)目在被掛起后需要在后臺(tái)運(yùn)行一段時(shí)間,使有足夠的時(shí)間來(lái)完成與服務(wù)器對(duì)接的操作,或者需要一直運(yùn)行的需求;如果需要,則在APP被掛起后,申請(qǐng)后臺(tái),來(lái)延長(zhǎng)后臺(tái)運(yùn)行時(shí)間。
APP申請(qǐng)后臺(tái)運(yùn)行的方式有幾種:
播放音樂(lè)
定位
Newsstand downloads
fetch 等;
這里主要說(shuō)下后臺(tái)播放無(wú)聲音樂(lè)(其實(shí)是不播放),采用哪種方式,對(duì)應(yīng)勾選上圖;我的項(xiàng)目中有音頻播放需求,如果沒(méi)有,那就找一個(gè)播放音頻的理由,或者用其他方式實(shí)現(xiàn)。
實(shí)現(xiàn)
這里采用了兩個(gè)單例:電話監(jiān)控(XKTelManager)、后臺(tái)運(yùn)行(XKBGRunManager),電話監(jiān)控可以忽略,視情況而用;采用單例是為了方便管理;
XKTelManager.h
#import <Foundation/Foundation.h>@interface XKTelManager : NSObject///是否在后臺(tái)運(yùn)行@property (nonatomic,assign) BOOL inBackgroundRun;+ (XKTelManager *)sharedManager;/** 來(lái)電監(jiān)聽 */- (void)startMonitor;@end
XKTelManager.m
#import "XKTelManager.h"#import "XKBGRunManager.h"#import <CoreTelephony/CTCallCenter.h>#import <CoreTelephony/CTCall.h>static XKTelManager *_sharedManger;@interface XKTelManager()@property (nonatomic, strong) CTCallCenter *callCenter;@end@implementation XKTelManager+ (XKTelManager *)sharedManager{ static dispatch_once_t onceTelSingle; dispatch_once(&onceTelSingle, ^{ if (!_sharedManger) { _sharedManger = [[XKTelManager alloc]init]; } }); return _sharedManger;}- (instancetype)init{ self = [super init]; if (self) { _inBackgroundRun = NO; } return self;}#pragma mark -********* 監(jiān)聽電話相關(guān)- (void)startMonitor { __weak typeof(self) weakSelf = self; _callCenter = [[CTCallCenter alloc] init]; _callCenter.callEventHandler = ^(CTCall * call) { ///如果已經(jīng)進(jìn)入后臺(tái)了,不做任何操作 if (weakSelf.inBackgroundRun) { return; } ///APP未進(jìn)入后臺(tái) if ([call.callState isEqualToString:CTCallStateDisconnected]){ NSLog(@"電話 --- 斷開連接"); [[XKBGRunManager sharedManager] stopBGRun]; } else if ([call.callState isEqualToString:CTCallStateConnected]){ NSLog(@"電話 --- 接通"); } else if ([call.callState isEqualToString:CTCallStateIncoming]){ NSLog(@"電話 --- 待接通"); [[XKBGRunManager sharedManager] startBGRun]; } else if ([call.callState isEqualToString:CTCallStateDialing]){ NSLog(@"電話 --- 撥號(hào)中"); [[XKBGRunManager sharedManager] startBGRun]; } else { NSLog(@"電話 --- 無(wú)操作"); } };}@end
XKBGRunManager.h
#import <Foundation/Foundation.h>@interface XKBGRunManager : NSObject+ (XKBGRunManager *)sharedManager;/** 開啟后臺(tái)運(yùn)行 */- (void)startBGRun;/** 關(guān)閉后臺(tái)運(yùn)行 */- (void)stopBGRun;@end
XKBGRunManager.m
#import "XKBGRunManager.h"///循環(huán)時(shí)間static NSInteger _circulaDuration = 60;static XKBGRunManager *_sharedManger;@interface XKBGRunManager()@property (nonatomic,assign) UIBackgroundTaskIdentifier task;///后臺(tái)播放@property (nonatomic,strong) AVAudioPlayer *playerBack;@property (nonatomic, strong) NSTimer *timerAD;///用來(lái)打印測(cè)試@property (nonatomic, strong) NSTimer *timerLog;@property (nonatomic,assign) NSInteger count;@end@implementation XKBGRunManager{ CFRunLoopRef _runloopRef; dispatch_queue_t _queue;}+ (XKBGRunManager *)sharedManager{ static dispatch_once_t onceRunSingle; dispatch_once(&onceRunSingle, ^{ if (!_sharedManger) { _sharedManger = [[XKBGRunManager alloc]init]; } }); return _sharedManger;}/// 重寫init方法,初始化音樂(lè)文件- (instancetype)init { if (self = [super init]) { [self setupAudioSession]; _queue = dispatch_queue_create("com.audio.inBackground", NULL); //靜音文件 NSString *filePath = [[NSBundle mainBundle] pathForResource:@"****" ofType:@"mp3"]; NSURL *fileURL = [[NSURL alloc] initFileURLWithPath:filePath]; self.playerBack = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:nil]; [self.playerBack prepareToPlay]; // 0.0~1.0,默認(rèn)為1.0 self.playerBack.volume = 0.01; // 循環(huán)播放 self.playerBack.numberOfLoops = -1; } return self;}- (void)setupAudioSession { // 新建AudioSession會(huì)話 AVAudioSession *audioSession = [AVAudioSession sharedInstance]; // 設(shè)置后臺(tái)播放 NSError *error = nil; [audioSession setCategory:AVAudioSessionCategoryPlayback withOptions:AVAudioSessionCategoryOptionMixWithOthers error:&error]; if (error) { NSLog(@"Error setCategory AVAudioSession: %@", error); } NSLog(@"%d", audioSession.isOtherAudioPlaying); NSError *activeSetError = nil; // 啟動(dòng)AudioSession,如果一個(gè)前臺(tái)app正在播放音頻則可能會(huì)啟動(dòng)失敗 [audioSession setActive:YES error:&activeSetError]; if (activeSetError) { NSLog(@"Error activating AVAudioSession: %@", activeSetError); }}/** 啟動(dòng)后臺(tái)運(yùn)行 */- (void)startBGRun{ [self.playerBack play]; [self applyforBackgroundTask]; ///確保兩個(gè)定時(shí)器同時(shí)進(jìn)行 dispatch_async(_queue, ^{ self.timerLog = [[NSTimer alloc] initWithFireDate:[NSDate date] interval:1 target:self selector:@selector(log) userInfo:nil repeats:YES]; self.timerAD = [[NSTimer alloc] initWithFireDate:[NSDate date] interval:_circulaDuration target:self selector:@selector(startAudioPlay) userInfo:nil repeats:YES]; _runloopRef = CFRunLoopGetCurrent(); [[NSRunLoop currentRunLoop] addTimer:self.timerAD forMode:NSDefaultRunLoopMode]; [[NSRunLoop currentRunLoop] addTimer:self.timerLog forMode:NSDefaultRunLoopMode]; CFRunLoopRun(); });}/** 申請(qǐng)后臺(tái) */- (void)applyforBackgroundTask{ _task =[[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{ dispatch_async(dispatch_get_main_queue(), ^{ [[UIApplication sharedApplication] endBackgroundTask:_task]; _task = UIBackgroundTaskInvalid; }); }];}/** 打印 */- (void)log{ _count = _count + 1; NSLog(@"_count = %ld",_count)}/** 檢測(cè)后臺(tái)運(yùn)行時(shí)間 */- (void)startAudioPlay{ _count = 0; dispatch_async(dispatch_get_main_queue(), ^{ if ([[UIApplication sharedApplication] backgroundTimeRemaining] < 61.0) { NSLog(@"后臺(tái)快被殺死了"); [self.playerBack play]; [self applyforBackgroundTask]; } else{ NSLog(@"后臺(tái)繼續(xù)活躍呢"); }///再次執(zhí)行播放器停止,后臺(tái)一直不會(huì)播放音樂(lè)文件 [self.playerBack stop]; });}/** 停止后臺(tái)運(yùn)行 */- (void)stopBGRun{ if (self.timerAD) { CFRunLoopStop(_runloopRef); [self.timerLog invalidate]; self.timerLog = nil; // 關(guān)閉定時(shí)器即可 [self.timerAD invalidate]; self.timerAD = nil; [self.playerBack stop]; } if (_task) { [[UIApplication sharedApplication] endBackgroundTask:_task]; _task = UIBackgroundTaskInvalid; }}@end
最后在 AppDelegate.m 對(duì)應(yīng)的方法中,實(shí)現(xiàn)開啟和停止后臺(tái)運(yùn)行即可!
感謝你能夠認(rèn)真閱讀完這篇文章,希望小編分享的“iOS怎樣實(shí)現(xiàn)后臺(tái)長(zhǎng)時(shí)間運(yùn)行”這篇文章對(duì)大家有幫助,同時(shí)也希望大家多多支持創(chuàng)新互聯(lián),關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,更多相關(guān)知識(shí)等著你來(lái)學(xué)習(xí)!
分享文章:iOS怎樣實(shí)現(xiàn)后臺(tái)長(zhǎng)時(shí)間運(yùn)行
網(wǎng)站地址:http://muchs.cn/article40/jsojho.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供服務(wù)器托管、ChatGPT、標(biāo)簽優(yōu)化、動(dòng)態(tài)網(wǎng)站、全網(wǎng)營(yíng)銷推廣、網(wǎng)站排名
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)