iOS程序进入后台后十分钟以内就会被系统kill掉,我想要程序进入后台后仍然运行计时功能,怎么解决呢?apache
方法一:可使用记录开始时间和获取当前时间的时间差进行处理bash
仍是直接上代码: 下面的代码是两种倒计时的方法和处理方法服务器
// // UIButton+SYTimerBtn.m // 倒计时按钮 // // Created by ZSY on 2018/7/2. // Copyright © 2018年 ZSY. All rights reserved. // #import "UIButton+SYTimerBtn.h" @implementation UIButton (SYTimerBtn) static NSTimer *timer; static long long startvalue; static NSTimeInterval count; static NSString *title; static dispatch_source_t gcdTimer; /** 倒计时方法一 @param duration 时间 */ - (void)sy_beginTouchdownWithDuration:(NSTimeInterval)duration { if (timer) { [self endTimer]; } startvalue = [self currentTime]; title = self.titleLabel.text; count = duration; timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(sy_updateTitle) userInfo:nil repeats:YES]; [[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes]; self.userInteractionEnabled = NO; } - (void)sy_stopDown { [self endTimer]; [self setTitle:title forState:UIControlStateNormal]; self.userInteractionEnabled = YES; } - (void)sy_updateTitle { long long currentvalue = [self currentTime]; int tmp = (int)(currentvalue - startvalue); if (tmp >= 59) { count = 1; } else if (tmp <= 0) { count = 60; } else { count = 60 - tmp; } NSString *string = [NSString stringWithFormat:@"%lds", (long)count]; [self setTitle:string forState:UIControlStateNormal]; NSLog(@"%f", count); if (count <= 1) { [self sy_stopDown]; } } /** 倒计时方法二 */ - (void)sy_startTime { if (gcdTimer) { [self endTimer]; } __block long long startvalue = [self currentTime]; // 倒计时开始时间 dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); gcdTimer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue); dispatch_source_set_timer(gcdTimer, dispatch_walltime(NULL, 0), 1.0*NSEC_PER_SEC, 0); // 每秒执行 __block int totlal = 60; dispatch_source_set_event_handler(gcdTimer, ^{ int timeout = 0; long long currentvalue = [self currentTime]; int tmp = (int)(currentvalue - startvalue); if (tmp >= totlal) { timeout = 0; } else if (tmp <= 0) { timeout = totlal; } else { timeout = totlal - tmp; } if (timeout <= 0) { //倒计时结束,关闭 [self endTimer]; dispatch_async(dispatch_get_main_queue(), ^{ [self setTitle:@"获取验证码" forState:UIControlStateNormal]; self.userInteractionEnabled = YES; }); } else { dispatch_async(dispatch_get_main_queue(), ^{ [self setTitle:[NSString stringWithFormat:@"%lds", (long)timeout] forState:UIControlStateNormal]; self.userInteractionEnabled = NO; }); } }); dispatch_resume(gcdTimer); } - (void)endTimer { if (timer) { [timer invalidate]; timer = nil; } if (gcdTimer) { dispatch_source_cancel(gcdTimer); gcdTimer = nil; } } - (void)dealloc { [self endTimer]; } - (long long)currentTime { NSDate *date = [NSDate dateWithTimeIntervalSinceNow:0]; NSTimeInterval a = [date timeIntervalSince1970]; return (long long)a; } @end
当一个 iOS 应用被送到后台,它的主线程会被暂停。你用 NSThread 的 detachNewThreadSelector:toTar get:withObject:类方法建立的线程也被挂起了。app
咱们假设有这么一种状况:async
当咱们的应用程序从前台被送到了后台。ide
这时候,咱们的程序将执行委托方法 applicationDidEnterBackground。可是,这时候,应用程序只给了咱们可怜的一点点时间(也就是秒级别的)来处理东西,而后,全部的线程都被挂起了。函数
而实际中,咱们可能须要更长的时间来完成咱们的须要的必要操做:oop
1.咱们须要在应用程序推到后台时,可以有足够的时间来完成将数据保存到远程服务器的操做。ui
2.有足够的时间记录一些须要的信息操做。spa
怎么办?!由于咱们须要的时间可能会有点长,而默认状况下,iOS没有留给咱们足够的时间。
方法二:向iOS申请,在后台完成一个Long-Running Task任务
当一个 iOS 应用被送到后台,它的主线程会被暂停。你用 NSThread 的 detachNewThreadSelector:toTar get:withObject:类方法建立的线程也被挂起了。
若是你想在后台完成一个长期任务,就必须调用 UIApplication 的 beginBackgroundTaskWithExpirationHandler:实例方法,来向 iOS 借点时间。
默认状况下,若是在这个期限内,长期任务没有被完成,iOS 将终止程序。
怎么办?可使用 beginBackgroundTaskWithExpirationHandler:实例方法,来向 iOS 再借点时间。
既然是借时间,那么就须要有一些约定俗成的方式。
1. 项目的AppDelegate文件中
声明一个 UIBackgroundTaskIdentifier ,至关于一个借据吧。告诉iOS,咱们的程序将要借更多的时间来完成 Long-Running Task 任务。
var mtimer: Timer = Timer() var backIden: UIBackgroundTaskIdentifier = 0 var count: NSInteger = 0
2. 在applicationDidEnterBackground方法中,完成借据的流程
func applicationDidEnterBackground(_ application: UIApplication) { // 使用这个方法来释放公共的资源、存储用户数据、中止咱们定义的定时器(timers)、而且存储在程序终止前的相关信息。 // 若是,咱们的应用程序提供了后台执行的方法,那么,在程序退出时,这个方法将代替applicationWillTerminate方法的执行。 mtimer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(countAction), userInfo: nil, repeats: true) RunLoop.current.add(mtimer, forMode: .commonModes) beginTask() } // 当应用程序掉到后台时,执行该方法 // 当一个 iOS 应用被送到后台,它的主线程会被暂停。你用 NSThread 的 detachNewThreadSelector:toTar get:withObject:类方法建立的线程也被挂起了。 // 若是你想在后台完成一个长期任务,就必须调用 UIApplication 的 beginBackgroundTaskWithExpirationHandler:实例方法,来向 iOS 借点时间。 // 默认状况下,若是在这个期限内,长期任务没有被完成,iOS 将终止程序。 // 怎么办?可使用 beginBackgroundTaskWithExpirationHandler:实例方法,来向 iOS 再借点时间。 func beginTask() { // 标记一个长时间运行的后台任务将开始 // 经过调试,发现,iOS给了咱们额外的10分钟(600s)来执行这个任务。 backIden = UIApplication.shared.beginBackgroundTask(expirationHandler: { [weak self] in // //在时间到以前会进入这个block,通常是iOS7及以上是3分钟。按照规范,在这里要手动结束后台,你不写也是会结束的(听说会crash) // 咱们须要在次Block块中执行一些清理工做。 // 若是清理工做失败了,那么将致使程序挂掉 // 清理工做须要在主线程中用同步的方式来进行 self?.endBack() }) } // 完成后,要告诉iOS,任务完成,提交完成申请“好借好还”: func endBack() { DispatchQueue.main.async { [weak self] in guard let strongself = self else { return } self?.mtimer.invalidate()// 中止定时器 // 每一个对 beginBackgroundTaskWithExpirationHandler:方法的调用,必需要相应的调用 endBackgroundTask:方法。这样,来告诉应用程序你已经执行完成了。 // 也就是说,咱们向 iOS 要更多时间来完成一个任务,那么咱们必须告诉 iOS 你何时能完成那个任务。 // 也就是要告诉应用程序:“好借好还”嘛。 // 标记指定的后台任务完成 UIApplication.shared.endBackgroundTask(strongself.backIden) // 销毁后台任务标识符 strongself.backIden = UIBackgroundTaskInvalid } } @objc func countAction() { count = count + 1 } func applicationWillEnterForeground(_ application: UIApplication) { endBack() }
3.记住,借和换必须成双成对!
具体的解释,我也写在了方法中,若是有错误之处,还但愿可以指正!谢谢!
4.若是,程序提早完成了,也能够提早结束:
UIApplication.shared.endBackgroundTask(backIden)
backIden = UIBackgroundTaskInvalid
方法三:其精髓就是:利用苹果给出的三种类型的程序能够保持在后台运行:音频播放类,位置更新类等,我利用了苹果给出的音频播放类的这个“特权”来知足我程序上的要求
步骤一:在Info.plist中,添加"Required background modes"键,value为:App plays audio
步骤二:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease]; // Override point for customization after application launch. NSError *setCategoryErr = nil; NSError *activationErr = nil; [[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error: &setCategoryErr]; [[AVAudioSession sharedInstance] setActive: YES error: &activationErr]; self.window.backgroundColor = [UIColor whiteColor]; [self.window makeKeyAndVisible]; return YES; }
步骤三:将如下代码添加到appDelegate文件中的- (void)applicationDidEnterBackground:(UIApplication *)application函数,也可添加到在具体类中注册的应用进入后台后的通知方法
- (void)applicationDidEnterBackground:(UIApplication *)application{ UIApplication* app = [UIApplication sharedApplication]; __block UIBackgroundTaskIdentifier bgTask; bgTask = [app beginBackgroundTaskWithExpirationHandler:^{ dispatch_async(dispatch_get_main_queue(), ^{ if (bgTask != UIBackgroundTaskInvalid) { bgTask = UIBackgroundTaskInvalid; } }); }]; dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ dispatch_async(dispatch_get_main_queue(), ^{ if (bgTask != UIBackgroundTaskInvalid) { bgTask = UIBackgroundTaskInvalid; } }); }); }