Niko
Niko

Reputation: 147

Swift - Force a user to enter input (i.e. not blank input) in a UIAlertController

I want to query a user for his or her name in one of my apps. I'd like to have a check to make sure that the user entered a non-blank string and then re-prompt the user with an error message if the input is invalid. So far this is what I have:

while name == "" {
        name = promptUserForName()
}

And the promptUserForName( ) method is this:

private func promptUserForName() -> String {
    let alert = UIAlertController(title: "Enter your name:", message: nil, preferredStyle: .Alert)

    // Presents a keyboard for user to enter name
    var userInputField: UITextField?
    alert.addTextFieldWithConfigurationHandler { (textField: UITextField!) in
        userInputField = textField
    }

    var name: String = ""

    let defaultAction = UIAlertAction(title: "OK", style: .Default, handler: {(action) -> Void in
        if let userInfo = userInputField!.text {
            name = userInfo
        }
    })

    alert.addAction(defaultAction)
    self.presentViewController(alert, animated: true, completion: nil)
    return name
}

Unfortunately, the while loop just loops infinitely without prompting the user and waiting for a response. Is there a way to make this work, perhaps by putting the while loop within the promptUserForName( ) method? Thanks.

Upvotes: 2

Views: 864

Answers (1)

Jonathan Chan
Jonathan Chan

Reputation: 354

Don't use a while-loop. Just check whether the name is blank in the alert's completion handler. If it is blank, call promptUserForName again; otherwise do whatever you need to do. You probably shouldn't return anything from this method, because it's asynchronous; instead, pass the name into another method from within the alert's completion handler.

Upvotes: 2

Related Questions