How to Show an Alert in Swift

In this tutorial, you will learn how to create and present an alert dialog in Swift.

An alert dialog in Swift is created using a UIAlertController class. The below Swift code snippets demonstrate how to:

  • Create a new alert message using UIAlertController,
  • How to present an alert dialog to the user,
  • How to add one or more action buttons and how to handle button events,
  • You will also learn how to change the UIAlertController style.

If you are interested in video lessons on how to write Unit tests and UI tests to test your Swift mobile app, check out this page: Unit Testing Swift Mobile App

Creating an Alert

To create a new alert dialog, we will need to use a UIAlertController class. The below code snippet demonstrates how to create and how to present a dialog message.

Note: The below code snippet will create an alert dialog with no action buttons. This means that the user will not be able to dismiss it. See the next code snippet to learn how to add action buttons.

// Create a new alert 
var dialogMessage = UIAlertController(title: "Attention", message: "I am an alert message you cannot dissmiss.", preferredStyle: .alert)

// Present alert to user
self.present(dialogMessage, animated: true, completion: nil)

UIAlertController with no buttons

Adding Action Buttons to Alert Dialog

The above Swift code snippet creates and displays an alert message but it does not contain any action buttons and thus the user will not have any means to dismiss it. To create an action button that the user can tap on, we will need to create a new instance of an UIAlertAction class and add it to our alert object.

 // Create new Alert
 var dialogMessage = UIAlertController(title: "Confirm", message: "Are you sure you want to delete this?", preferredStyle: .alert)
 
 // Create OK button with action handler
 let ok = UIAlertAction(title: "OK", style: .default, handler: { (action) -> Void in
     print("Ok button tapped")
  })
 
 //Add OK button to a dialog message
 dialogMessage.addAction(ok)

 // Present Alert to 
 self.present(dialogMessage, animated: true, completion: nil)

UIAlertController with one button

To add one more button to UIAlertController simply create a new UIAlertAction object and add it to the alert. The below code snippet demonstrates how to create UIAlertController with two action buttons.

// Create Alert
var dialogMessage = UIAlertController(title: "Confirm", message: "Are you sure you want to delete this?", preferredStyle: .alert)

// Create OK button with action handler
let ok = UIAlertAction(title: "OK", style: .default, handler: { (action) -> Void in
    print("Ok button tapped")
})

// Create Cancel button with action handlder
let cancel = UIAlertAction(title: "Cancel", style: .cancel) { (action) -> Void in
    print("Cancel button tapped")
}

//Add OK and Cancel button to an Alert object
dialogMessage.addAction(ok)
dialogMessage.addAction(cancel)

// Present alert message to user
self.present(dialogMessage, animated: true, completion: nil)

UIAlertController with two buttons

Make an Action Button Call a Function

When the user taps on one of the action buttons, we want to call a function that will perform some operation. The below Swift code snippet demonstrates how to make an OK button call a function.

import UIKit

class ViewController: UIViewController {
 
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
  
        displayAlert()
    }
    
    func displayAlert() {
        // Declare Alert message
        let dialogMessage = UIAlertController(title: "Confirm", message: "Are you sure you want to delete this?", preferredStyle: .alert)
        
        // Create OK button with action handler
        let ok = UIAlertAction(title: "OK", style: .default, handler: { (action) -> Void in
            print("Ok button tapped")
            self.deleteRecord()
        })
        
        // Create Cancel button with action handlder
        let cancel = UIAlertAction(title: "Cancel", style: .cancel) { (action) -> Void in
            print("Cancel button tapped")
        }
        
        //Add OK and Cancel button to dialog message
        dialogMessage.addAction(ok)
        dialogMessage.addAction(cancel)
        
        // Present dialog message to user
        self.present(dialogMessage, animated: true, completion: nil)
        
    }
    
    func deleteRecord()
    {
        print("Delete record function called")
    }
    
}

Adding a Text Field to Alert

You can add a text field to an alert dialog. The below code example demonstrates how to add a UITextField to UIAlertController.

// Declare Alert message
let dialogMessage = UIAlertController(title: "Alert", message: "Are you sure you want to delete this?", preferredStyle: .alert)

// Add text field
dialogMessage.addTextField(configurationHandler: { textField in
    textField.placeholder = "Type in your PIN for it to work"
})

When an action button tapped, you can access the text field and read its value.

// Create OK button with action handler
let ok = UIAlertAction(title: "OK", style: .default, handler: { (action) -> Void in
    print("Ok button tapped")
    print("PIN code typed = \(dialogMessage.textFields?.first?.text ?? "")")
})

UIAlertController with UITextField

Video tutorial

Have a look at this video tutorial to see how to create and present UIViewController.

Leave a Reply

Your email address will not be published. Required fields are marked *

Free Video Lessons

Enter your email and stay on top of things,

Subscribe!