0

I am currently trying to learn and advance my skills more as a Swift developer, and this may come across as a dumb question but I'm curious.

Problem
In my code I am constantly repeating UIAlertController creation and presentation code so much that it looks sloppy. Also with Dispatching it to the main thread, it takes up to 5 lines, and I repeat this code throughout my project multiple times, on multiple View Controllers. So instead I have created a "Utilities" class and in that class I have a function that displays a UIAlertController.

Question
What I was wondering is, is this bad coding practice? Is it sloppy to constantly call on this function from another class, creating a new UIAlertController constantly? Does this slow my application done? Or is this perfectly fine?

Code incase it matters:

class Utils {

func displayError(viewController: UIViewController, title: String, message: String, action: UIAlertAction?) {
    let ac = UIAlertController(title: title,
                               message: message,
                               preferredStyle: .alert)

    if action == nil {
        ac.addAction(UIAlertAction(title: "Ok", style: .cancel))
    } else {
        ac.addAction(action!)
    }

    DispatchQueue.main.async {
        viewController.present(ac, animated: true)
    }
}
}

Thank you in advanced.

Julian
  • 98
  • 1
  • 11

2 Answers2

1

For swift 5, iOS 13*

incl. resolve: 'keyWindow' was deprecated in iOS 13.0

I prefer to keep my messages in a separate class class GlobMessage: UIAlertController {, calling them from various VC’s. Based on answer from Youssef and How to resolve: 'keyWindow' was deprecated in iOS 13.0

class GlobMessage: UIAlertController {
    static func MessageXYZ(){
        ///needs 'extension UIWindow'
        ///'static' allows to call from various VC‘s

        
        if let keyWindow = UIWindow.key {
            //found calling VC 

            //create text for Message
            let header:String = //"⚠️ deactivated!"

            let body01:String = """

                your message here.
                Second row of message.
                """

            // assemble body 
            let body:String = body01 //+ body02 + body03 + body04 + body05 + body06 + body07 + body08 + body09 + body10 + body11 + body12 + body13 + body14 + body15 + body16 + body17 + body18 + body19 + body20

            //buttons with functions
            let OK = UIAlertAction(title: "OK", style: .default) {
               UIAlertAction in
               //your code here
           }
            let NOK = UIAlertAction(title: "❌not jet", style: .destructive) {
                UIAlertAction in
                //your code here
            }

            //assemble message
            let Message = UIAlertController(title: header, message: body, preferredStyle: .alert)
            Message.addAction(OK)
            //Message.addAction(NOK)
            
            //present message
            keyWindow.rootViewController!.present(Message, animated: true, completion: nil)
        }//end if let keyWindow
    }//end static func MessageXYZ()

}//end class GlobMessage


//MARK: -
extension UIWindow {
    /// source: https://stackoverflow.com/questions/57134259/how-to-resolve-keywindow-was-deprecated-in-ios-13-0
    /// what’s the calling VC?:
    /// Usage:
    /// if let keyWindow = UIWindow.key {
    ///    // Do something
    ///    ....
    ///    keyWindow.rootViewController!.present(Message, animated: true, completion: nil)
    /// }//end if let keyWindow
    ///
    static var key: UIWindow? {
        if #available(iOS 13, *) {
            return UIApplication.shared.windows.first { $0.isKeyWindow }
        } else {
            return UIApplication.shared.keyWindow
        }//end if else
    }//end static var key
}//end extension UIWindow

Community
  • 1
  • 1
RvdH
  • 72
  • 6
0

Instead of passing the view controller as a parameter, you could use your window's rootviewcontroller property to display the alert. Here is an example:

class Utils {

    static func displayAlert(title: String, message: String) {

        let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
        let defaultAction = UIAlertAction(title: "Default", style: .default, handler: nil)
        alertController.addAction(defaultAction)

        guard let viewController = UIApplication.shared.keyWindow?.rootViewController else {
            fatalError("keyWindow has no rootViewController")
            return
        }

        viewController.present(alertController, animated: true, completion: nil)
    }

}

Don't forget to define your function as static to be able to call it this way:

Utils.displayAlert(title: "Hello", message: "This is an alert")
Youssef
  • 1
  • 2