2016-04-29 55 views
0

我有這個應用程序,當應用程序從背景回來或第二次啓動和所有其他的後續應用程序將呈現密碼屏幕。如何在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 { 
    } 
} 

回答

0

最好的辦法是創建一個後臺任務和您在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 
} 
相關問題