问题
I`m trying to perform a segue if its the first time the app is loading. I can see my print message in the debugger, but the Perform Segue is not working. I don't get any errors. Can somebody please tell me whats wrong?
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:
You can't use performSegue() from within viewDidLoad(). Move it to viewDidAppear().
At viewDidLoad() time, the current view isn't even attached to the window yet, so it's not possible to segue yet.
回答2:
I think you can also put your segue into a Dispatch.main.async
DispatchQueue.main.async {
if isFirstLaunch == false {
performSegue(withIdentifier: "setPassword", sender: self)
print("testFalse")
} else {
performSegue(withIdentifier: "setPassword", sender: self)
print("testTrue")
}
}
回答3:
You can also use a different approach - change the main window's rootViewController
to the view controller of your choice depending on isFirstLaunch
boolean
UIApplication.shared.keyWindow?.rootViewController = setPasswordViewController
来源:https://stackoverflow.com/questions/45653825/perform-segue-in-viewdidload