Search code examples
iosswiftxcodexcode8

create a display alert function globally and call it from any view controller


func displayalert(title:String, message:String, vc:UIViewController)
{
    let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert)
    alert.addAction((UIAlertAction(title: "OK", style: .default, handler: { (action) -> Void in

        self.dismiss(animated: true, completion: nil)

    })))

    vc.present(alert, animated: true, completion: nil)


}


this is the function i have used.i tried to call it like this,

 displayalert1(title:"dsfvasdcs", message:"easfSDXCSDZX", vc:validateOTPViewController())

it is returning error "BAD ACCESS". the vc.present is running like a loop. I cant understand what the problem is.


Solution

  • I run your code and it working fine. I thing you would pass self in vc.

     self.displayalert(title: "Title", message: "Some Message", vc: self)
    

    You can also make an extension of UIViewController-

       extension UIViewController {
              // Your Function...
        }
    

    Now You can globally access this function from any view controller, Just by typing-

        self.displayalert(title: "Title", message: "Some Message", vc: self)