如何在Swift中的某个时间在后台展示UIViewController?
问题描述:
我有这个应用程序,当应用程序从背景回来或第二次启动和所有其他的后续应用程序将呈现密码屏幕。如何在Swift中的某个时间在后台展示UIViewController?
但我只需要呈现,如果应用程序在背景上至少30秒,并且不低于此。
我该怎么做?
的代码,我要加载当前密码的屏幕是AppDelegate.swift:
func applicationDidBecomeActive(application: UIApplication) {
//Load lock screen
let topController = self.topViewControllerWithRootViewController(UIApplication.sharedApplication().delegate?.window??.rootViewController)
let userDefaults = NSUserDefaults.standardUserDefaults()
let displayedWalkthrough = userDefaults.boolForKey("Walk")
if displayedWalkthrough {
let main : UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let lockVC = main.instantiateViewControllerWithIdentifier("LockVC") as! LockVC
topController.presentViewController(lockVC, animated: true, completion: nil)
} else {
}
}
答
最好的办法是创建一个后台任务和您在applicationDidBecomeActive()
阅读30秒后设置一个标志。您必须使用beginBackgroundTaskWithExpirationHandler
,here。例如(请task
全球):
在进入背景:
func applicationDidEnterBackground(application: UIApplication) {
task = application.beginBackgroundTaskWithExpirationHandler({})
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(30 * Double(NSEC_PER_SEC))), dispatch_get_main_queue()) {
NSUserDefaults.standardUserDefaults.setBool(true, forKey: "lock")
}
application.endBackgroundTask(task)
}
上启动:
func applicationDidBecomeActive(application: UIApplication) {
if NSNSUserDefaults.standardUserDefaults.boolForKey("lock") {
// show lock
}
application.endBackgroundTask(task)
NSUserDefaults.standardUserDefaults.setBool(true, forKey: "lock")
// rest of your code
}