Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift Displaying Alerts best practices

I have various controllers in my app that all require validation, and when validation fails, I want to display an alert with the errors. Is there some best practice/design pattern for doing this? I could simply create a static function in a Helper class like so:

static func displayAlert(message: String, buttonTitle: String, vc: UIViewController) {     let alertController = UIAlertController(title: "", message: message, preferredStyle: .Alert)      let okAction = UIAlertAction(title: buttonTitle, style: .Default, handler: nil)     alertController.addAction(okAction)      vc.presentViewController(alertController, animated: true, completion: nil) } 

But then I need to pass the view controller..which seems like bad practice. I could shoot off a notification and observe it, but that seems like overkill. Am I overthinking this, or is there some more acceptable way to go about handling something like this?

like image 339
Ryan Bobrowski Avatar asked Apr 14 '15 17:04

Ryan Bobrowski


2 Answers

I ended up creating an extension for UIViewController and creating the alert function there:

extension UIViewController {   func alert(message: String, title: String = "") {     let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)     let OKAction = UIAlertAction(title: "OK", style: .default, handler: nil)     alertController.addAction(OKAction)     self.present(alertController, animated: true, completion: nil)   }   } 
like image 199
Ryan Bobrowski Avatar answered Sep 19 '22 08:09

Ryan Bobrowski


Swift 4

I wanted this same functionality for myself, so I made a full extension. To use it, create a new swift file in your project and name it whatever you'd like. Place the following code inside:

import UIKit  extension UIViewController {      func presentAlertWithTitle(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)             }))         }         self.present(alertController, animated: true, completion: nil)     } } 

To use it (which so many people don't actually show, which can lead to confusion for a newbie like myself):

presentAlertWithTitle(title: "Test", message: "A message", options: "1", "2") { (option) in     print("option: \(option)")     switch(option) {         case 0:             print("option one")             break         case 1:             print("option two")         default:             break     } } 
like image 23
Sigex Avatar answered Sep 22 '22 08:09

Sigex