Swift: вставьте предупреждающий ящик с текстовым вводом (и сохраните текстовый ввод)

В одном из моих viewController я хочу, чтобы появилось сообщение alert box, которое запрашивает user для ввода этой информации. Затем я хочу, чтобы пользователь сохранил этот ввод с помощью NSUserDefaults. Как я могу это достичь?

Заранее благодарю!

Ответы

Ответ 1

Проверьте это:

let alertController = UIAlertController(title: "Email?", message: "Please input your email:", preferredStyle: .Alert)

let confirmAction = UIAlertAction(title: "Confirm", style: .Default) { (_) in
    if let field = alertController.textFields![0] as? UITextField {
        // store your data
        NSUserDefaults.standardUserDefaults().setObject(field.text, forKey: "userEmail")
        NSUserDefaults.standardUserDefaults().synchronize()
    } else {
        // user did not fill field
    }
}

let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel) { (_) in }

alertController.addTextFieldWithConfigurationHandler { (textField) in
    textField.placeholder = "Email"
}

alertController.addAction(confirmAction)
alertController.addAction(cancelAction)

self.presentViewController(alertController, animated: true, completion: nil)

Ответ 2

SWIFT 3

func presentAlert() {
    let alertController = UIAlertController(title: "Email?", message: "Please input your email:", preferredStyle: .alert)

    let confirmAction = UIAlertAction(title: "Confirm", style: .default) { (_) in
        if let field = alertController.textFields?[0] {
            // store your data
            UserDefaults.standard.set(field.text, forKey: "userEmail")
            UserDefaults.standard.synchronize()
        } else {
            // user did not fill field
        }
    }

    let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) { (_) in }

    alertController.addTextField { (textField) in
        textField.placeholder = "Email"
    }

    alertController.addAction(confirmAction)
    alertController.addAction(cancelAction)

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

Ответ 3

В быстрой 3

let alertController = UIAlertController(title: "SecureStyle", message: "SecureStyle AlertView.", preferredStyle: UIAlertControllerStyle.Alert)
alertController.addTextFieldWithConfigurationHandler { (textField : UITextField) -> Void in
            textField.secureTextEntry = true
            textField.placeholder = "Password"
        }
let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel) { (result : UIAlertAction) -> Void in
            print("Cancel")
        }
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default) { (result : UIAlertAction) -> Void in
            print(alertController.textFields?.first?.text)
        }
alertController.addAction(cancelAction)
alertController.addAction(okAction)
self.presentViewController(alertController, animated: true, completion: nil)