Show and dismis UIAlertController in Swift 4
 
Notifications
Clear all

Show and dismis UIAlertController in Swift 4  

  RSS
william.t18
(@william-t18)
New Member
Show and dismis UIAlertController in Swift 4

I declared a global variable for UIAlertViewController for me to be able to show and dismiss it in different method inside my class. I displayed two kinds of alert: First, alert with button which will be displayed when an error is encountered or to display an information message. Second is an alert without button which will be displayed like a progress message mypremiercreditcard.

Here is the sample code:

private var alert: UIAlertController? // global declaration

private func showProgressMessage(sender viewController: UIViewController, message alertMessage: String)
{
DispatchQueue.main.async
{
self.alert= UIAlertController(title: "", message: alertMessage, preferredStyle: .alert)
viewController.present(self.alert!, animated: true, completion: nil)
}
}

private func showAlertMessage(sender viewController: UIViewController, title alertTitle: String, message alertMessage: String)
{
DispatchQueue.main.async
{
self.alert= UIAlertController(title: alertTitle, message: alertMessage, preferredStyle: .alert)

self.alert!.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
viewController.present(self.alert!, animated: true, completion: nil)
}
}

private func method1()
{
DispatchQueue.global().async
{
// some code here
self.showProgressMessage(sender: self, message: "Processing...")
// some code here
}
}

private func method2()
{
// some code here
self.alert!.dismiss(animated: false)
{
self.showAlertMessage(sender: self, message: "Done")
}

self.displayOtherViewController()
}

private func displayOtherViewController()
{
self.alert?.dismiss(animated: false)
{
if let viewController = self.storyboard?.instantiateViewController(withIdentifier: "Sample")
{
let view = viewController as! SampleViewController

view .modalTransitionStyle = .crossDissolve

self.present(view , animated: true, completion: nil)
}
}
}

In method2, displaying the alert again will take a few seconds to display, same with the view controller. What is the proper way to show and dismis the UIAlertController in Swift 4?

Posted : 24/12/2018 7:59 am
Share: