Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift: Insert Alert Box with Text Input (and Store Text Input )

In one of my viewController, I want to make an alert box appear that prompts the user to type this information.Then, I want the user to store this input using NSUserDefaults. How can I achieve this?

Thank you in advance!

like image 750
l-spark Avatar asked Apr 22 '15 20:04

l-spark


2 Answers

Check this out:

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

let confirmAction = UIAlertAction(title: "Confirm", style: .default) { (_) in
  guard let textFields = alertController.textFields,
    textFields.count > 0 else {
      // Could not find textfield
      return
  }

  let field = textFields[0]
  // store your data
  UserDefaults.standard.set(field.text, forKey: "userEmail")
  UserDefaults.standard.synchronize()
}

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)
like image 116
Andrei Papancea Avatar answered Oct 21 '22 22:10

Andrei Papancea


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 emailTextField = alertController.textFields?[0] {
            // do your stuff with emailTextField
        } 
    }

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

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

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

    present(alertController, animated: true, completion: nil)
}
like image 35
Yaroslav Dukal Avatar answered Oct 21 '22 20:10

Yaroslav Dukal