UIAlertController made easy

Once I read somewhere on the internet, creating an Alert in IOS is comparatively harder than JavaScript. I’m not a big fan of HTML & CSS, but I do know a little Javascript, creating an Alert popup in Javascript is pretty much easier, just like this.

alert(“I am an alert box!”);

That’s all it takes to create an alert using JS. If you want to try other types of popups using JS, check out here.

But, let’s try with Swift.

let alertVC = UIAlertController(title: “Alert”, message: “Testing”, preferredStyle: .alert)
let okAction = UIAlertAction(title: “OK”, style: .default, handler: nil)
alertVC.addAction(okAction)

Looking at the above, IOS needs a little extra code, doesn’t it?
But, that’s not the end, let’s make it lesser, reusable and better.
How about this?

        alert(title: “Alert”, message: “Auto dismiss in 4 sec”, autoDismissTime: 4.0)

I’ve written an extension for UIViewController, which uses just the above one line code to display an Alert popup.

There are 2 styles in UIAlertController such as Alert and ActionSheet, you can use them and generally 3 types of Alerts like Alert popup, Alert with Action, Alert with prompt. These types are also available in Javascript.

The extension covers all, I’d tried to make it as simple and usable as possible, you can download the source code from github and play with it, try to customize.

After all, we have so many options in Alert popup compared to Javascript, and now after they are not harder as they were before using custom extensions.

Happy coding.

Leave a comment