How to display an Alert Popup in iOS Swift

January 21, 2019

Often times in an iOS application you will need to prompt the user with an alert to either display something or have the user perform an action (ie Confirm action). UIKit has a built in alert called UIAlertController and UIAlertAction that allows you to do this.

Let's take a look:

ViewController.swift

let alert = UIAlertController(title: "Alert", message: "Message", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "ok", style: .default, handler: { action in
      switch action.style{
      case .default:
            print("default")
      case .cancel:
            print("cancel")

      case .destructive:
            print("destructive")
}}))

self.present(alert, animated: true, completion: nil)

You may add more actions by using the addAction function.