Error message when performing show segue and save userdefault: View is not in the window heirarch

时间:2017-03-02 23:39:26

标签: ios swift xcode nsuserdefaults

I'm having a problem with the alert not displaying. I know it works because it prints to my console. I also tested the alertpopup in a viewDidAppear method and it worked. I've read some post and it maybe because of me trying to perform a segue and save a userdefault at the same time. I keep getting "Warning: Attempt to present... whose view is not in the window hierarchy". Any way to fix it or an explanation of what I'm doing wrong?

import UIKit

class StartMenuViewController : UIViewController
{
    @IBOutlet var nameInput: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }


    @IBAction func startAction(_ sender: Any)
    {
        if nameInput.text == ""
        {
            print("This is working")
            createAlert(title: "Warning", message: "Need to enter name")
        }

        UserDefaults.standard.set(nameInput.text, forKey: "UserName")
    }
    override func viewDidAppear(_ animated: Bool)
    {


        if let name = UserDefaults.standard.object(forKey: "UserName") as? String
        {
            nameInput.text = name
        }

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func createAlert (title: String, message: String)
    {
        let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert)

        alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: { (action) in
            alert.dismiss(animated: true, completion: nil)
        }))

        self.present(alert, animated: true, completion: nil)
    }

}

0 个答案:

没有答案