Search code examples
iosswiftuialertview

UIAlertView shared class with return bool in Swift 4


protocol AlertDelegate: AnyObject {
      func didGetResponse(text: String?)
}
class AlertClass{

    weak var delegate: AlertDelegate?
    static let sharedInstance = AlertClass()
    //Show alert
    func alertWindow(title: String, message: String) {
        DispatchQueue.main.async(execute: {
            let alertWindow = UIWindow(frame: UIScreen.main.bounds)
            alertWindow.rootViewController = UIViewController()
            alertWindow.windowLevel = UIWindow.Level.alert + 1

            let alert2 = UIAlertController(title: title, message: message, preferredStyle: .alert)
            let defaultAction1 = UIAlertAction(title: "Yes", style: .destructive, handler: { action in
                print("Yes")
            })
            let defaultAction2 = UIAlertAction(title: "No", style: .destructive, handler: { action in
                print("No")
            })
            alert2.addAction(defaultAction1)
            alert2.addAction(defaultAction2)

            alertWindow.makeKeyAndVisible()

            alertWindow.rootViewController?.present(alert2, animated: true, completion: nil)



        })
    }
}

How can I return bool value in this class?


Solution

  • class AlertClass{//This is shared class
    
        weak var delegate: AlertDelegate?
        static let sharedInstance = AlertClass()
    
        //Show alert
        func alertWindow(title: String, message: String, completion:@escaping (_ result: Bool) -> Void) {
            let alertWindow = UIWindow(frame: UIScreen.main.bounds)
            alertWindow.rootViewController = UIViewController()
            alertWindow.windowLevel = UIWindow.Level.alert + 1
    
            let alert2 = UIAlertController(title: title, message: message, preferredStyle: .alert)
            let defaultAction1 = UIAlertAction(title: "Yes", style: .destructive, handler: { action in
                completion(true)
    
            })
            let defaultAction2 = UIAlertAction(title: "No", style: .destructive, handler: { action in
                print("No")
                completion(false)
            })
            alert2.addAction(defaultAction1)
            alert2.addAction(defaultAction2)
    
            alertWindow.makeKeyAndVisible()
    
            alertWindow.rootViewController?.present(alert2, animated: true, completion: nil)
        }
    }
    
    alert.alertWindow(title: "", message: "Checking Completion") { (result) in
        if result{
            print("It's yes")
        }
        else {
            print("It's no")
        }
    }