Search code examples
iosswiftuialertcontroller

How to create uialertcontroller in global swift


I'm trying to create uialertcontroller in Config.swift file as follow.

static func showAlertMessage(titleStr:String, messageStr:String) -> Void {
    let window : UIWindow?
    let alert = UIAlertController(title: titleStr, message: messageStr, preferredStyle: UIAlertControllerStyle.Alert);
    self.window!.presentViewController(alert, animated: true, completion: nil)
}

problem is I've found problem in self.window!.

Type 'Config' has no member 'window'

Please let me know how to solve that issue.


Solution

  • self.window would mean that there's a window object in this class, and it's not the case.

    You would need to use your let window : UIWindow? with window?.presentViewController(alert, animated: true, completion: nil), but this won't help, since this window does not actually represent any existing window, and it's not a view controller anyway.

    So I suggest you pass the actual view controller you'll be using to the method:

    static func showAlertMessage(vc: UIViewController, titleStr:String, messageStr:String) -> Void {
        let alert = UIAlertController(title: titleStr, message: messageStr, preferredStyle: UIAlertControllerStyle.Alert);
        vc.presentViewController(alert, animated: true, completion: nil)
    }
    

    and you call it from a class where a UIViewController object is available.