tara tandel
tara tandel

Reputation: 550

Passing the function of the UIAlertAction to the UIAlertController extension

I want to have a base UIAlertController and I want to use it in different classes by just passing the buttons and their closures. To achieve this, I created an extension from UIAlertController like below:

extension UIAlertController {
    func showAlert(buttons: [ButtonsAction]?) -> UIAlertController {
        let alert = self
        guard let alertButtons = buttons else {
            return alert
        }
        for button in alertButtons {
            let alertAction = UIAlertAction(title: button.title, style: button.style, handler: {action in
                button.handler()
            })
            alert.addAction(alertAction)
        }

        return alert
    }
}

for my buttons I have a struct:

struct ButtonsAction {
    let title: String!
    let style: UIAlertAction.Style
    let handler: () -> Void
}

In one of my viewControllers I have a function which shows the alert. In that function I have a title and a message then I want to have 1 button to dismiss the alert. The function is something like this:

    func fetchFaild(title: String, message: String) {
        let buttons = ButtonsAction.init(title: "cancel", style: .cancel, handler: {action in
            //here I want to dissmiss the alert I dont know how
        })

        let alert = UIAlertController(title: title, message: message, preferredStyle: .alert).showAlert(buttons: buttons)
        alert.show(self, sender: nil)

    }

I have problem adding buttons to the Alert and I don't know how to add actions to the buttons. I know this is not the best practice here. If any one knows any example or any tutorial that can help me achieve this I really appreciate it.

Upvotes: 1

Views: 377

Answers (1)

vadian
vadian

Reputation: 285250

An extension of UIViewController might be a more reasonable solution and the ButtonsAction struct seems to be redundant.

 extension UIViewController {
    func showAlert(title: String, message: String, actions: [UIAlertAction], completion: (() -> Void)? = nil)  {
        let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
        actions.forEach{alertController.addAction($0)}
        self.present(alertController, animated: true, completion: completion)
    }
}

class MyController : UIViewController {

    func fetchFailed(title: String, message: String) {
        let actions = [UIAlertAction(title: "Cancel", style: .cancel, handler: { (action) in
            print("Cancel tapped")
        })]
       showAlert(title: title, message: message, actions: actions)
    }

}

Upvotes: 2

Related Questions