Search code examples
iosiphoneswiftuialertcontroller

How to create reusable UIAlertcontroller?


I want to create a reusable UIAlertController class for my project.I tried the following code.But my alert is not showing.What is the wrong in my code or any code help.This is my alert class

class AlertView: NSObject {

 class func showAlert(view: UIViewController , message: String){

        let alert = UIAlertController(title: "Warning", message: message, preferredStyle: UIAlertControllerStyle.Alert)
        alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))
        view.presentViewController(alert, animated: true, completion: nil)
    }
}

and i am calling this in my another view controller like

class ViewController: UIViewController {

  override func viewDidLoad() {
      super.viewDidLoad()
      AlertView.showAlert(self, message: "Test alert")
      // Do any additional setup after loading the view, typically from a nib.
   }
}

Solution

  • present your alert in main_queue

    class AlertView: NSObject {
    
        class func showAlert(view: UIViewController , message: String) {
            let alert = UIAlertController(title: "Warning", message: message, preferredStyle: UIAlertControllerStyle.Alert)
            alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))
    
            dispatch_async(dispatch_get_main_queue(), {
                view.presentViewController(alert, animated: true, completion: nil)
            })
        }
    }
    
    class ViewController: UIViewController {
    
        override func viewDidLoad() {
            super.viewDidLoad()
            AlertView.showAlert(self, message: "Test alert")
            // Do any additional setup after loading the view, typically from a nib.
        }
    }