Creating an alert

If you have ever owned an iphone then you have seen an alert message. These are essentially popups that are standard for iOS. An alert message pops up on your screen and lets you know something (hopefully) pretty important. While working on my weather app I learned how to create an alert message letting a user know that something is wrong (no problems yet though!).

It turns out that creating a alert message is very easy, all you need to know is a few different class names and you are good to go. To create an alert message you need to access something known as the UIAlertController. You do this by creating a constant, like networkIssueController and having it equal UIAlertController. Next you open a set of parenthesis. You should get some hints from xcode, but if not, you want the one that says: (title: “Title of alert”, message: “Your message goes here”, Preferred Style: UIAlertControllerStyle).

After that you need to let the view controller to run. You do this by typing self.PresentViewController and opening some parenthesis. Xcode will autofill and you just have a few more choices to make inside of the parenthesis, under ‘networkIssueController’ type .alert, for animated: true, smf completion: nil.

Right now if you run the app you should have an alert pop up, but have no buttons to close it. The code should look something like this:


let networkIssueController = UIAlertController(title: “Title of alert”, message: “Your message goes here”, Preferred Style: UIAlertControllerStyle)

self.PresesntViewController(networkIssueController: .alert, animation: true, completion: nil)

The last thing you need to do is add a button o r two to be able to close out the alert. To do this you need to create a constant, let’s call it okButton, and then have that equal to UIAlertAction. After UIAlertAction create a set of parenthesis, Xcode will give a tip, choose the one that has title, style, and handler. For title just enter what you want the button to say within quotation marks. For style choose .defaut, and for handler just write nil.


let okButton = UIAlertAction(title: “ok”, style: .default, handler: nil)

Run your code and you should now have an alert message with a butt