iOS Alert - UIAlertController With Examples

In this tutorial, we’ll be discussing the UIAlertController class and how it is handy to create different types of Alerts in our iOS Application.

iOS Alert – UIAlertController

UIAlertController is used to configure alerts and actionsheets with various actions to choose from.

We have already ActionSheets in another tutorial. Here we’ll be focussing on the alerts style of UIAlertController.

Along with the actions, we can also add an image logo. We can set textfield inputs in the Alerts as well that we shall see shortly.

UIAlertController is often used to ask the user to open a type of application. Example: Call/Message. Camera/Gallery.

Choose among the different Map apps.

Default Alerts

A basic UIAlertController Alert dialog can be created in the following way in Swift.


let alertController = UIAlertController(title: "JournalDev.com", message: "Default Alert Dialog", preferredStyle: .alert)
let defaultAction = UIAlertAction(title: "OK", style: .default, handler: nil)
alertController.addAction(defaultAction)
self.present(alertController, animated: true, completion: nil)

A title, message, and the preferred style are passed. Every Button in the UIAlertController is a UIAlertAction.

The UIAlertAction buttons are of three styles: default, destructive, cancel. The destructive style is in color red.

Action Buttons

Every UIALertAction has a handler argument wherein we add our logic of the action to be performed.


let alertController = UIAlertController(title: "JournalDev", message: "Alert With Actions", preferredStyle: .alert)
        let action1 = UIAlertAction(title: "OK", style: .default) { (action:UIAlertAction) in
            print("You've pressed OK")
            alertController.dismiss(animated: true, completion: nil)
        }
        let action2 = UIAlertAction(title: "Cancel", style: .cancel) { (action:UIAlertAction) in
            print("You've pressed Cancel")
        }
        let action3 = UIAlertAction(title: "Delete", style: .destructive) { (action:UIAlertAction) in
            print("You've pressed the destructive")
        }
        alertController.addAction(action1)
        alertController.addAction(action2)
        alertController.addAction(action3)
        self.present(alertController, animated: true, completion: nil)

In the above code, we have added log statements in the Swift closures. You can pass your own custom functions here as well.

UIAlertController With Call, Messsage, Open Maps

In the following code, each of our action buttons will be used for calling, messaging, opening a third party application from the Alert Dialog.


let application:UIApplication = UIApplication.shared
                let alert = UIAlertController(title: "Your Title", message: "Select one of the apps", preferredStyle: .alert)
                let callAction = UIAlertAction(title: "Call", style: .default, handler: { (action) in
                    let phoneNumber: String = "tel:/1234567890"
                    application.open(URL(string: phoneNumber)!, options: [:], completionHandler: nil)
                })
                let messageAction = UIAlertAction(title: "Message", style: .default, handler: { (action) in
                    application.open(URL(string: "sms:123456")!, options: [:], completionHandler: nil)
                })
                let mapsAction = UIAlertAction(title: "Apple Maps", style: .destructive, handler: { (action) in
                    let targetURL = URL(string: "https://maps.apple.com/?q=cupertino")!
                    application.open(targetURL, options: [:], completionHandler: nil)
                })
                alert.addAction(callAction)
                alert.addAction(messageAction)
                alert.addAction(mapsAction)
                self.present(alert, animated: true, completion: nil)

The url schema to pass the phone number is: “tel:/(phone_number_pass_here)”
For opening a third party application such as Apple Maps, we need to use it’s pre-defined custom schema.

To open Google Maps Application we first need to check if the application is installed or not:


if (UIApplication.shared.canOpenURL(URL(string:"comgooglemaps://")!))
        {
            UIApplication.shared.openURL(URL(string:
                "comgooglemaps://?saddr=&daddr=(Float(latitude!)),(Float(longitude!))&directionsmode=driving")! as URL)
        } else
        {
            NSLog("Can't use com.google.maps://");
        }

Add Image Logo And Launch a URL

We can add an image logo to each of the action buttons.

Also, we can set an action that launches the URL in the default web browser of our iOS Device.


let alertController = UIAlertController(title: "JournalDev.com", message: "Alert Dialog with Image", preferredStyle: .alert)
        let imageAction = UIAlertAction(title: "Website", style: .default, handler: {
            (action) in
            UIApplication.shared.open(URL(string: "https://www.journaldev.com")!, options: [:], completionHandler: nil)
        })
        imageAction.setValue(UIImage(named: "logo")?.withRenderingMode(UIImageRenderingMode.alwaysOriginal), forKey: "image")
        let okAction = UIAlertAction(title: "OK", style: .default, handler: nil)
        okAction.setValue(UIColor.brown, forKey: "titleTextColor")
        alertController.addAction(imageAction)
        alertController.addAction(okAction)
        self.present(alertController, animated: true, completion: nil)

For each action, we can set the image filename defined in our Assets folder of the XCode project.

To set the same color for each of the action buttons do the following:


alertController.view.tintColor = UIColor.orange

Adding a TextField


let alert = UIAlertController(title: "Login", message: "Please enter the details below", preferredStyle: .alert)
        alert.addTextField{ textField -> Void in
            textField.placeholder = "Username"
            textField.textColor = UIColor.blue
        }
        alert.addTextField{ textField -> Void in
            textField.placeholder = "Password"
            textField.textColor = UIColor.black
            textField.isSecureTextEntry = true
        }
        let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
        alert.addAction(cancelAction)
        self.present(alert, animated: true, completion: nil)

Inside the addTextField function, we can configure the TextField. All of the TextFields would be stacked vertically.

Let’s merge all of these in our XCode iOS Application.

MainStoryboard

ios-alertcontroller-storyboard

We have connected each of the Buttons to the ViewController.swift and created an IBAction function for each of them.

In the Assets folder import a png image file. Make sure the key name is the same as the one you set in the ViewController.swift below:


import UIKit
class ViewController: UIViewController {
    @IBAction func showAlert(_ sender: Any) {
        let alertController = UIAlertController(title: "JournalDev.com", message: "Default Alert Dialog", preferredStyle: .alert)
        let defaultAction = UIAlertAction(title: "OK", style: .default, handler: nil)
        alertController.addAction(defaultAction)
        self.present(alertController, animated: true, completion: nil)
    }
    @IBAction func showAlertWithActions(_ sender: Any) {
        let alertController = UIAlertController(title: "JournalDev", message: "Alert With Actions", preferredStyle: .alert)
        let action1 = UIAlertAction(title: "OK", style: .default) { (action:UIAlertAction) in
            print("You've pressed OK")
            alertController.dismiss(animated: true, completion: nil)
        }
        let action2 = UIAlertAction(title: "Cancel", style: .cancel) { (action:UIAlertAction) in
            print("You've pressed Cancel")
        }
        let action3 = UIAlertAction(title: "Delete", style: .destructive) { (action:UIAlertAction) in
            print("You've pressed the destructive")
        }
        alertController.addAction(action1)
        alertController.addAction(action2)
        alertController.addAction(action3)
        self.present(alertController, animated: true, completion: nil)
    }
    @IBAction func showAlertWithTextField(_ sender: Any) {
        let alert = UIAlertController(title: "Login", message: "Please enter the details below", preferredStyle: .alert)
        alert.addTextField{ textField -> Void in
            //TextField configuration
            textField.placeholder = "Username"
            textField.textColor = UIColor.blue
        }
        alert.addTextField{ textField -> Void in
            //TextField configuration
            textField.placeholder = "Password"
            textField.textColor = UIColor.black
            textField.isSecureTextEntry = true
        }
        let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
        alert.addAction(cancelAction)
        self.present(alert, animated: true, completion: nil)
    }
    @IBAction func showAlertWithCallMapsMessage(_ sender: Any) {
                let application:UIApplication = UIApplication.shared
                let alert = UIAlertController(title: "Your Title", message: "Select one of the apps", preferredStyle: .alert)
                let callAction = UIAlertAction(title: "Call", style: .default, handler: { (action) in
                    let phoneNumber: String = "tel:/1234567890"
                    application.open(URL(string: phoneNumber)!, options: [:], completionHandler: nil)
                })
                let messageAction = UIAlertAction(title: "Message", style: .default, handler: { (action) in
                    application.open(URL(string: "sms:123456")!, options: [:], completionHandler: nil)
                })
                let mapsAction = UIAlertAction(title: "Apple Maps", style: .destructive, handler: { (action) in
                    let targetURL = URL(string: "https://maps.apple.com/?q=cupertino")!
                    application.open(targetURL, options: [:], completionHandler: nil)
                })
                alert.addAction(callAction)
                alert.addAction(messageAction)
                alert.addAction(mapsAction)
                self.present(alert, animated: true, completion: nil)
    }
    @IBAction func showAlertWithImageLogo(_ sender: Any) {
        let alertController = UIAlertController(title: "JournalDev.com", message: "Alert Dialog with Image", preferredStyle: .alert)
        //alertController.view.tintColor = UIColor.orange
        let imageAction = UIAlertAction(title: "Website", style: .default, handler: {
            (action) in
            UIApplication.shared.open(URL(string: "https://www.journaldev.com")!, options: [:], completionHandler: nil)
        })
        imageAction.setValue(UIImage(named: "logo")?.withRenderingMode(UIImageRenderingMode.alwaysOriginal), forKey: "image")
        let okAction = UIAlertAction(title: "OK", style: .default, handler: nil)
        okAction.setValue(UIColor.brown, forKey: "titleTextColor")
        alertController.addAction(imageAction)
        alertController.addAction(okAction)
        self.present(alertController, animated: true, completion: nil)
    }
    override func viewDidLoad() {
        super.viewDidLoad()
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}

The output of the above application in action is given below:
ios alert UIAlertController

Notice that when we press Call, iOS automatically re-confirms the number to be dialed. iOS does this to enhance the UX by asking for the user’s permission before switching the application.

This brings an end to this tutorial. You can download the project from the link below:

By admin

Leave a Reply

%d bloggers like this: