Creating a Toast Message in IOS with Swift
Today we are going to use two major components in the IOS ecosystem. The first one is UIAlertController framework which is part of UIKit, it handles those alerts you receive on your IOS device. The other component of IOS we are going to use is Asynchronous code compilation which puts a piece of code on a different thread that can be called with a specific delay. We use the combination of these to display an alert with no buttons, and dismiss it using Async after a specified delay. This may sound confusing, however when you look at the code bellow it will make more sense. Ok let’s dive into some code.
Toast(Title: "Title", Text: "Text", delay: 5)
The line above is how we will call our Toast method. If you have worked with Alerts in IOS before you will see a connection in what parts of the alert we passed to the function parameters. The Alert title, and message where passed in as function parameters so you can set your own custom title, and message for the Toast. We also passed in a Integer called delay which is the amount of seconds you want your Toast to show. Now lets take a look at the function itself.
func Toast(Title:String ,Text:String, delay:Int) -> Void { let alert = UIAlertController(title: Title, message: Text, preferredStyle: .alert) self.present(alert, animated: true) let deadlineTime = DispatchTime.now() + .seconds(delay) DispatchQueue.main.asyncAfter(deadline: deadlineTime, execute: { alert.dismiss(animated: true, completion: nil) }) }
First we assign a initialized UIAlertController with its necessary fields to present our alert. The UIAlertController is what’s responsible for presenting the alert to us, thus we have to pass in the title, message, and style. In this example I leave the style to default, however you may need to change this to .actionSheet if you are running your app on a iPad. The self.present field under the last discussed field displays the alert for us with animations enabled, and no actions taken after alert is shown. The deadlineTime variable is in-charge of setting the delay of our block of code. In the lines bellow we execute our code in the main thread, except we are adding a deadline of when to compile this block of code. inside of this Dispatche function we call alert.dismiss with animations enabled, and no action taken after being dismissed.
Bellow is how our Toast will behave with a 2 second delay.