IOS 后台挂起,向IOS申请后台无限时间
经过证明,即使时执行Long-Running Task 任务,当程序被调到后台后,也是有时间限制的。一般为10分总(600s)。如何向程序申请无限时间呢?!
那就欺骗iOS系统吧。让它感觉你的程序还是在运行。那就在后台用 AVAudioPlayer无限循环播放一个音频文件。呵呵,如果播放一个无声音的音频文件呢?!!
操作步骤:
1.在plish文件中加入背景播放的支持。
加入项:Required background modes。并设置为:audio
2.初始化一个AVAudioPlayer音频,并且无限制的播放下去。
- (void)viewDidLoad
{
[super viewDidLoad];
dispatch_queue_t dispatchQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(dispatchQueue, ^(void) {
NSError *audioSessionError = nil;
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
if ([audioSession setCategory:AVAudioSessionCategoryPlayback error:&audioSessionError]){
NSLog(@"Successfully set the audio session.");
} else {
NSLog(@"Could not set the audio session");
}
NSBundle *mainBundle = [NSBundle mainBundle];
NSString *filePath = [mainBundle pathForResource:@"mySong" ofType:@"mp3"];
NSData *fileData = [NSData dataWithContentsOfFile:filePath];
NSError *error = nil;
self.audioPlayer = [[AVAudioPlayer alloc] initWithData:fileData error:&error];
if (self.audioPlayer != nil){
self.audioPlayer.delegate = self;
[self.audioPlayer setNumberOfLoops:-1];
if ([self.audioPlayer prepareToPlay] && [self.audioPlayer play]){
NSLog(@"Successfully started playing...");
} else {
NSLog(@"Failed to play.");
}
} else {
}
});
}