2017-08-12 79 views
1

如果在第一次加载应用程序时尝试执行segue, 我可以在调试器中看到我的打印消息,但Perform Segue不起作用。我没有得到任何错误。 有人可以告诉我什么是错的?在ViewDidLoad中执行Segue

import UIKit 
import LocalAuthentication 
let isFirstLaunch = UserDefaults.isFirstLaunch() 
extension UserDefaults { 
    // check for is first launch - only true on first invocation after app install, false on all further invocations 
    // Note: Store this value in AppDelegate if you have multiple places where you are checking for this flag 
    static func isFirstLaunch() -> Bool { 
     let hasBeenLaunchedBeforeFlag = "hasBeenLaunchedBeforeFlag" 
     let isFirstLaunch = !UserDefaults.standard.bool(forKey: hasBeenLaunchedBeforeFlag) 
     if (isFirstLaunch) { 

      UserDefaults.standard.set(true, forKey: hasBeenLaunchedBeforeFlag) 
      UserDefaults.standard.synchronize() 
     } 
     return isFirstLaunch 
    } 
} 

class loginVC: UIViewController { 





    override func viewDidLoad() { 

     super.viewDidLoad() 

     if isFirstLaunch == false { 
      performSegue(withIdentifier: "setPassword", sender: self) 
      print("testFalse") } 
      else { 
      performSegue(withIdentifier: "setPassword", sender: self) 
      print("testTrue")} 


     //  Do any additional setup after loading the view, typically from a nib. 




    } 
+1

什么打印在日志中? – Vyacheslav

+0

'testTrue'为第一次启动,'testFalse'为其他? – Vyacheslav

+1

正确。日志中的第一行是testFalse –

回答

5

您不能在viewDidLoad()中使用performSegue()。将其移动到viewDidAppear()。

在viewDidLoad()时间,当前视图甚至没有附加到窗口,所以它不可能继续。

+0

谢谢Smartcat。将代码移到ViewDidAppear(),它现在工作正常! –

0

您也可以使用不同的方法 - 改变主窗口的rootViewController取决于isFirstLaunch布尔

UIApplication.shared.keyWindow?.rootViewController = setPasswordViewController

0

我想你也可以把你的赛格瑞成Dispatch.main.async

您所选择的视图控制器
DispatchQueue.main.async { 
     if isFirstLaunch == false { 
      performSegue(withIdentifier: "setPassword", sender: self) 
      print("testFalse") 
     } else { 
      performSegue(withIdentifier: "setPassword", sender: self) 
      print("testTrue") 
     } 
    }