定时器后台运行

ios中如何让程序的定时器在程序进入后台的时候依然继续有效?
只需添加以下代码到中applicationDidEnterBackground(application: UIApplication)

func applicationDidEnterBackground(application: UIApplication) {
application.beginReceivingRemoteControlEvents()
        var bgTask : UIBackgroundTaskIdentifier?
        bgTask = application.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
                }
            })
        }
}

真机iPhone4s测试过十分钟和三十分钟都没有问题

你可能感兴趣的:(定时器后台运行)