Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling presentViewController from custom class

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)...

like image 757
Pieter Avatar asked Dec 05 '22 03:12

Pieter


2 Answers

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.

EDIT:

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.

like image 103
Duncan C Avatar answered Dec 18 '22 16:12

Duncan C


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")
like image 21
Alex Zanfir Avatar answered Dec 18 '22 15:12

Alex Zanfir