UIAlertController in Swift and how to use them in Extension or in Custom Class

Shankar Madeshvaran
Developer in Making
5 min readJun 6, 2019
Photo by Max Nelson on Unsplash

In iOS 8.0 SKD, the changes of two commonly-used APIs in UIKit framework are less known. Both UIActionSheet and UIAlertView classes are now replaced by the UIAlertController class.

In iOS 8, whenever you want to display an alert message in your app, you should use UIAlertController instead the two deprecated classes. The action sheet and alert view become the style of the UIAlertController. When using UIAlertController, you associate actions with the controller and that the action is expressed as a block in Objective-C or closures in Swift.

In this article, you’ll learn how to use the UIAlertController class to display alert dialogs to the user of your iOS app. We’ll dive into setting up the alerts, responding to user actions, and getting input from the user with text fields.This article is specially written for beginner and also for the experienced iOS developers. Working with the UIAlertController is a fundamental topic for practical iOS developers.

Showing Alert using AlertController

func showAlert(message: String) {
let alertController = UIAlertController(title: “”, message: message, preferredStyle: .alert)
let okAction = UIAlertAction(title: “OK”, style: .default)
let cancelAction = UIAlertAction(title: “Cancel”, style: .cancel)
alertController.addAction(okAction)
alertController.addAction(cancelAction)
self.present(alertController, animated: true)
}

In above function, UIAlertController is used to display an alert in a any ViewController.By using UIAlertController, we can choose title & what message to show in alert and preferredStyle(.alert or .actionSheet).In UIAlertAction, we can choose style(.default,.cancel,.destructive) & title for the button in alert. The alert will be presented only on the ViewController & when calling showAlert(message: “Example Alert”) function, we present Alert in the current view controller where this function is called.

For example, self.present(alertController, animated: true,completion: { print(“This executes after UIAlertController is finishes Executing”)
})

After displaying UIAlertController we can use a completion block to execute actions,navigation etc,The same completion block is also used UIAlertAction,

For example, let cancelAction = UIAlertAction(title: “Cancel”, style: .cancel ,completion: { print(“This executes after cancel button is pressed ”)
})

Seperate Swift File To Display Alert:

For beginners the above function is helpful to understand and knowing how to display alert in iOS App.To reduce code,I think putting seperate file for Alerts make your code clean and also improves readability of your projects.

For example , instead of calling Internet Availability error message each time in ViewController, putting a common class will help maintaing the code easily.

Create a Swift file in your project and Name it Alert.swift

import Foundation
import UIKit

struct Alert {
static let internetAlertMessage = “Please check your internet connection and try again”
static let internetAlertTitle = “Internet Failure”

private static func showAlert(on vc:UIViewController,with title:String, message:String) {
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: “OK”, style: .default, handler: nil))
DispatchQueue.main.async {
vc.present(alert, animated: true, completion: nil)
}
}

//Show Common Alert like internet failure
static func showInternetFailureAlert(on vc:UIViewController){
showAlert(on: vc, with: internetAlertTitle, message: internetAlertMessage)
}
}

//Show Specific Alerts like Valid or Invalid
static func showInternetFailureAlert(on vc:UIViewController){
showAlert(on: vc, with: “Alert”, message: “Invalid”)
}
}

The above Alert.swift File, we have created an common function to display internet failure message.
In this methods we presented alert in DispatchQueue.main.async {} for better performance.It will present alert message in asynchronous main thread which will present smoothly without affecting any ongoing preoceses.

To use this function in your project we have call function Alert.showInternetFailureAlert(on: self)(). Instead of self ,you can use any viewcontroller.

showInternetFailureAlert(on: <UIViewController>) function will call showAlert(on: vc, with: internetAlertTitle, message: internetAlertMessage) function,but why need of another function when you can directly call showAlert() ,but use of showInternetFailureAlert(on: <UIViewController>) function helps to give seperate message & alerts. Internet alert is common function and you can give various alert messages throughout the app or use can simply use call Alert.showAlert(on vc:UIViewController,with title:String, message:String) function but need to make a function public not private.

UIAlertController in Extensions:

When working in projects that has too many xib or views used in viewcontroller,It is quite difficult to track which controller has been used to embed views or Xib.For that you need to use delegate to find which view controller is used by xibs.

I have an extension for UIViewController which you can present alert directly in the rootViewController of the project.It saves lot time to figure which viewController to show the alert.

import UIKit
extension UIViewController {
/// Display message in prompt view
///
/// — Parameters:
/// — title: Title to display Alert
/// — message: Pass string of content message
/// — options: Pass multiple UIAlertAction title like “OK”,”Cancel” etc
/// — completion: The block to execute after the presentation finishes.

func presentAlertWithTitleAndMessage(title: String, message: String, options: String…, completion: @escaping (Int) -> Void) {
let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
for (index, option) in options.enumerated() {
alertController.addAction(UIAlertAction.init(title: option, style: .default, handler: { (action) in
completion(index)
}))
}
topMostViewController().present(alertController, animated: true, completion: nil)
}

/// Get the top most view in the app
/// — Returns: It returns current foreground UIViewcontroller

func topMostViewController() -> UIViewController {
var topViewController: UIViewController? = UIApplication.shared.keyWindow?.rootViewController
while ((topViewController?.presentedViewController) != nil) {
topViewController = topViewController?.presentedViewController
}
return topViewController!
}

}

Extensions in Swift

Extensions add new functionality to an existing class, structure, enumeration, or protocol type. This includes the ability to extend types for which you do not have access to the original source code (known as retroactive modeling). Extensions are similar to categories in Objective-C. (Unlike Objective-C categories, Swift extensions do not have names.)

To access or use the above mentioned extension:

(i) Use window to get to rootViewController to present Alert
self.window?.rootViewController?.presentAlertWithTitle(title: “”, message: “Alert Using Extension ”, options: “OK”) { (option) in
//Dismiss the alert
}

(ii) Use Appdelegate to get to rootViewController to present Alert
AppDelegate.appDelegate().window?.rootViewController?.presentAlertWithTitle(title: “”, message: “Internet Failed”, options: “OK”) { (option) in
//Dismiss the alert
}

To get rootViewController in AppDelegate you should have this below class in AppDeleagate.swift.This function confirms the delegate of the AppDelegate and present in rootViewController.

class func appDelegate() -> AppDelegate {
return (UIApplication.shared.delegate! as? AppDelegate)!
}

By using this extension, you can present alert in any view controller because it is extended from UIViewController.This extension also accepts two or more UIAlertAction & also executes completion block.

Conclusion:

In this article, we learned about how to use and present UIAlertController in view controller easily and effectively.This article can also understand by new developer and also experienced developer.Extension is a really powerful feature in Swift Language. You can use your code to making more simple and understandable functionality. You can write separated and easy to manageable code as per your understanding, requirements.Thanks

Let’s connect!

You can find me on Twitter | LinkedIn | GitHub

--

--

Shankar Madeshvaran
Developer in Making

iOS and Web/React Js Developer. I write articles regarding Web, iOS ,React.Js concepts. Subscribe for more: https://shankarmadeshvaran.hashnode.dev