How to make sure input is formatted correctly in Swift

128 Views Asked by At

I have an app that is crashing when a user inputs the wrong format in a text frame. How can I 1)make sure the keyboard is the right type (which would be a number keyboard in my case) and 2) make it so the app doesn't crash if a wrong format is input? Here is my code for this button:

@IBAction func resetDistanceWalkedGoalButton(sender: AnyObject) {
    var distanceWalkedAlert = UIAlertController(title: "Distance Walked", message: "Current Goal: \(distanceWalkedGoal) miles – Enter a new goal. (e.g. '1.75')", preferredStyle: UIAlertControllerStyle.Alert)

    distanceWalkedAlert.addTextFieldWithConfigurationHandler {
        (textField) in
    }

    distanceWalkedAlert.addAction(UIAlertAction(title: "Submit", style: .Default, handler: {
        (action) in

        let textW = distanceWalkedAlert.textFields![0] as UITextField
        print(textW)

        textW.keyboardType = UIKeyboardType.NumberPad

        let distanceWalkedGoalFromAlert = Double(textW.text!)


        distanceWalkedGoal = distanceWalkedGoalFromAlert!

        print(distanceWalkedGoal)
        self.distanceWalkedGoalNumber.text = "\(distanceWalkedGoal)"

    }))

    distanceWalkedAlert.addAction(UIAlertAction(title: "Cancel", style: .Default, handler: {
        (action) in

        self.dismissViewControllerAnimated(true, completion: nil)


    }))

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



}
2

There are 2 best solutions below

0
Thành Ngô Văn On

you should setup properties for UItextfield in method addTextFieldWithConfigurationHandler and it will not crash

alertController.addTextFieldWithConfigurationHandler { (textField) in
        textField.placeholder = "Enter RSS Link here ..."
        textField.text = link
        textField.keyboardType = UIKeyboardType.NumberPad

        // add Notification to handle text input if you need
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.textDidChange), name: UITextFieldTextDidChangeNotification, object: linkTextField)

    }
0
Sweeper On

make sure the keyboard is the right type (which would be a number keyboard in my case)

Actually, you don't need to change any of your current code!

textW.keyboardType = .NumberPad

But note that iPads don't have a number pad keyboard. If you want to show a number pad on the iPad, you have to create your own.

make it so the app doesn't crash if a wrong format is input

This requires a little bit more work. In the action handler for the "Submit" action, do a little check after you convert the string to double:

distanceWalkedAlert.addAction(UIAlertAction(title: "Submit", style: .Default, handler: {
    (action) in

    let textW = distanceWalkedAlert.textFields![0] as UITextField
    print(textW)

    textW.keyboardType = UIKeyboardType.NumberPad

    let distanceWalkedGoalFromAlert = Double(textW.text!)

    guard distanceWalkedGoalFromAlert != nil else {
        // if code execution goes here, this means that invalid input is detected.
        // you can show another alert telling the user that here.
        return
    }

    distanceWalkedGoal = distanceWalkedGoalFromAlert!

    print(distanceWalkedGoal)
    self.distanceWalkedGoalNumber.text = "\(distanceWalkedGoal)"

}))

Or you can also try out WKTextFieldFormatter which blocks invalid input altogether.