Make a class comprises of the functions like UIAlertView, UIActivityIndicator and call them back in various viewControllers

163 Views Asked by At

This is my current code:

import UIKit

class classViewController: UIViewController {
  // The function i want to call in other view controllers..
  func alertView(title: String, message: String) {
    var alert:UIAlertController = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert)
        alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: { (action) -> Void in                
            self.dismissViewControllerAnimated(true, completion: nil)
        }))
    self.presentViewController(alert, animated: true, completion: nil)
  }
}

In the other view controller, where I've made an IBAction to perform this alertView, I have done this:

@IBAction func button(sender: AnyObject) {
  classViewController().alertView("title", message: "message")
}

When I run the app, after tapping the button I get this error, but no alertView:

Warning: Attempt to present on whose view is not in the window hierarchy!

1

There are 1 best solutions below

3
Duncan C On

Right. If you want to make a global class that displays alerts, you need to pass in a reference to the current view controller, and use that instead of "self" in calls like presentViewController.

Your class should probably not be a subclass of UIViewController, since it looks like you're never displaying it to the screen.

I created a Utils class that is a subclass of NSObject.

It has a method showAlertOnVC that looks like this:

  class func showAlertOnVC(targetVC: UIViewController?, var title: String, var message: String)
  {
    title = NSLocalizedString(title, comment: "")
    message = NSLocalizedString(message, comment: "")
    if let targetVC = targetVC
    {
      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)
    }
    else
    {
      println("attempting to display alert to nil view controller.")
      println("Alert title = \(title)")
      println("Alert message = \(message)")
    }
  }