I read this post and this one on how to call a presentViewController form outside a UIViewController subclass. In my case, the custom class is a subclass of NSObject. The following approach is the only one that works (from the examples I read):
UIApplication.sharedApplication().keyWindow?.rootViewController?.presentViewController(alertController, animated: true, completion: nil)
My question: is there a better solution that does not rely on the appDelegate (as I understood this approach is design-wise not very neat)...
I sometimes create a utilities class to display alerts and such. What I usually do is have my methods for presenting view controllers take the current view controller as a parameter. That approach works pretty well.
Here is an example method from a file Utils.swift in one of my projects. It defines a class function that displays a UIAlertController alert on the current view controller:
class Utils
{
static let sharedUtils = Utils()
class func showAlertOnVC(
targetVC: UIViewController,
var title: String,
var message: String)
{
title = NSLocalizedString(title, comment: "")
message = NSLocalizedString(message, comment: "")
let alert = UIAlertController(
title: title,
message: message,
preferredStyle: UIAlertControllerStyle.Alert)
let okButton = UIAlertAction(
title:"OK",
style: UIAlertActionStyle.Default,
handler:
{
(alert: UIAlertAction!) in
})
alert.addAction(okButton)
targetVC.presentViewController(alert, animated: true, completion: nil)
}
}
The code above defines a class Utils. Note that it does not have any base class, which is Ok in Swift.
Next it defines a public static variable sharedUtils that you can use to get access to the singleton Utils class.
Finally, it defines a class method showAlertOnVC
that can be used to display a UIAlertController alert on top of the current view controller. To use showAlertOnVC
you call it from the current view controller and pass self as the targetVC
parameter.
This in my opinion is the easiest solution:
class Utils {
static func displayTheAlert(targetVC: UIViewController, title: String, message: String){
let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction((UIAlertAction(title: "OK", style: .Default, handler: {(action) -> Void in
})))
targetVC.presentViewController(alert, animated: true, completion: nil)
}
}
// then to call it
Utils.displayTheAlert(self, title: "Fout", message: "Uw bestelling is nog niet klaar")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With