我们知道,到我们程序从前台退到后台(安home)键后,将执行程序的委托方法。
// 当应用程序掉到后台时,执行该方法
- (void)applicationDidEnterBackground:(UIApplication *)application
{
}
假设有这么一种情况:
当我们的应用程序从前台被送到了后台。
这时候,我们的程序将执行委托方法applicationDidEnterBackground。但是,这时候,应用程序只给了我们可怜的一点点时间(也就是秒级别的)来处理东西,然后,所有的线程都被挂起了。
而实际中,我们可能需要更长的时间来完成我们的需要的必要操作:
1.我们需要在应用程序推到后台时,能够有足够的时间来完成将数据保存到远程服务器的操作。
2.有足够的时间记录一些需要的信息操作。
怎么办?!因为我们需要的时间可能会有点长,而默认情况下,iOS没有留给我们足够的时间。
向iOS申请,在后台完成一个Long-Running Task任务
当一个 iOS 应用被送到后台,它的主线程会被暂停。你用 NSThread 的detachNewThreadSelector:toTar get:withObject:类方法创建的线程也被挂起了。
如果你想在后台完成一个长期任务,就必须调用 UIApplication 的 beginBackgroundTaskWithExpirationHandler:实例方法,来向 iOS 借点时间。
默认情况下,如果在这个期限内,长期任务没有被完成,iOS 将终止程序。
可以使用 beginBackgroundTaskWithExpirationHandler:实例方法,来向 iOS 再借点时间。
#import "AppDelegate.h"
@interface AppDelegate ()
@property (nonatomic, unsafe_unretained) UIBackgroundTaskIdentifier backgroundTaskIdentifier;
@property (nonatomic, strong) NSTimer *myTimer;
@property (nonatomic, assign) BOOL isFlag;
@end
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
return YES;
}
- (void)applicationWillResignActive:(UIApplication *)application {
}
- (void) endBackgroundTask{
dispatch_queue_t mainQueue = dispatch_get_main_queue();
AppDelegate *weakSelf = self;
dispatch_async(mainQueue, ^{
AppDelegate *strongSelf = weakSelf;
if (strongSelf != nil) {
NSTimeInterval time = [[NSDate date] timeIntervalSince1970]*1000;
NSInteger timeStamp = time/1000;
NSLog(@"\n\n\n\n\n\n\n%@\n\n\n\n\n\n",@(timeStamp).stringValue);
[strongSelf.myTimer invalidate];// 停止定时器
2.完成后,要告诉iOS,任务完成,提交完成申请“好借好还”:
// 每个对 beginBackgroundTaskWithExpirationHandler:方法的调用,必须要相应的调用 endBackgroundTask:方法。这样,来告诉应用程序你已经执行完成了。 也就是说,我们向 iOS 要更多时间来完成一个任务,那么我们必须告诉 iOS 你什么时候能完成那个任务,也就是要告诉应用程序:“好借好还”嘛。
// 标记指定的后台任务完成
[[UIApplication sharedApplication] endBackgroundTask:self.backgroundTaskIdentifier];
// 销毁后台任务标识符 strongSelf.backgroundTaskIdentifier = UIBackgroundTaskInvalid;
}
});
}
- (void)timeMethod:(NSTimer *)paramSender{
// backgroundTimeRemaining属性包含了程序留给我们的时间
NSTimeInterval backgroundTimeRemaining = [[UIApplication sharedApplication] backgroundTimeRemaining];
if (!self.isFlag) {
NSTimeInterval time = [[NSDate date] timeIntervalSince1970]*1000;
NSInteger timeStamp = time/1000;
NSLog(@"\n\n\n\n\n\n\n%@\n\n\n\n\n\n",@(timeStamp).stringValue);
self.isFlag = YES;
}
if (backgroundTimeRemaining == DBL_MAX) {
NSLog(@"background time remaining = undetermined");
NSTimeInterval time = [[NSDate date] timeIntervalSince1970]*1000;
NSInteger timeStamp = time/1000;
NSLog(@"%@",@(timeStamp).stringValue);
}else{
NSLog(@"background time remaining = %.02f seconds",backgroundTimeRemaining);
}
}
- (void)applicationDidEnterBackground:(UIApplication *)application {
1.注意在applicationDidEnterBackground方法中,完成借据的流程
self.backgroundTaskIdentifier = [application beginBackgroundTaskWithExpirationHandler:^{
[self endBackgroundTask];
}];
self.myTimer = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(timeMethod:) userInfo:nil repeats:YES];
}
通过这样测试申请的时间最多为4分钟.
还有一个办法就是向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.");
}
}
});
}
原文链接