All about Alerts

Sept 19, 2017   3 minutes to read



Basic Alerts

1
First we create a new "Single-View App" Project in Xcode (Shortcut: + + N).

2
Next, we are going to select the "ViewController.swift" file from the Project Navigator. For demonstration purpose, we're simply going to override the "viewDidAppear" function and extend it with our alert call. So that our alert pops up right after our view finished appearing.

All we have to do now is to type the keyword "viewDidAppear" inside the ViewController Class, and Xcode will autocomplete this override function for us.
//  ViewController.swift
import UIKit

class ViewController: UIViewController{
    override func viewDidLoad() {
        super.viewDidLoad()
    }
    
    override func viewDidAppear(_ animated: Bool) {
        // Here we will call our alert
    }

    ...
}

3
Now we are going to create our first alert by adding the following lines inside our previously created "viewDidAppear" function.
// Create the Alert Object
let alert = UIAlertController(title: "My Alert Title ", message:"My Alert Message", preferredStyle: .alert)

// *The following Snippets are added here BEFORE self.present(..)*

// Present the Alert on our View
self.present(alert, animated: true, completion: nil)
When we run our app now, we will see the alert popup, but there is no way to cancel the alert yet.


In order to cancel it, we need to add a button to our alert view. To do this, we simply add the following lines of code:
let cancel = UIAlertAction(title: "Cancel", style: .default, handler: nil)
alert.addAction(cancel)
As a result, we are now capable to create and dismiss alerts.


However, alerts are also capable of receiving and processing user input. We will now demonstrate this in our following steps.

4
To include a text input box inside an alert, all we have to do is further add the following lines:
alert.addTextField(configurationHandler: nil) // Inputbox 1
alert.addTextField(configurationHandler: nil) // Inputbox 2
When we run our app, we should now see the two input textfields.



5
To process the inputs, we need another action beside the cancel action. Here we will call it the save action.
let save = UIAlertAction(title: "Save", style: .default){
            (alertAction: UIAlertAction) in
            
            if let firstInput = alert.textFields?[0].text! {
                print(firstInput)
            }
            
            if let secondInput = alert.textFields?[1].text! {
                print(secondInput)
            }
}
Now we have to add it to our alert object as follows:
alert.addAction(save) // Similar to how we added the cancel button
As a result, we will see the users input in our console, when the save button is pressed.

Final Source Code

//  ViewController.swift
import UIKit
class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
    }
    
    override func viewDidAppear(_ animated: Bool) {
        let alert = UIAlertController(title: "My Alert Title ", message:"My Alert Message", preferredStyle: .alert)
        let save = UIAlertAction(title: "Save", style: .default){
            (alertAction: UIAlertAction) in
            
            if let firstInput = alert.textFields?[0].text! {
                print(firstInput)
            }
            
            if let secondInput = alert.textFields?[1].text! {
                print(secondInput)
            }
        }
        
        let cancel = UIAlertAction(title: "Cancel", style: .default, handler: nil)
        alert.addTextField(configurationHandler: nil)
        alert.addTextField(configurationHandler: nil)
        
        alert.addAction(save)
        alert.addAction(cancel)
        
        self.present(alert, animated: true, completion: nil)
    }
}