0

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!

Nathaniel Ford
  • 20,545
  • 20
  • 91
  • 102
Akshay Kheveria
  • 201
  • 1
  • 15

1 Answers1

0

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)")
    }
  }
Duncan C
  • 128,072
  • 22
  • 173
  • 272
  • u got the question correctly..sorry i am a beginner.. can u elucidate it more?? – Akshay Kheveria Jul 13 '15 at 00:12
  • i called this function in the IBAction in "viewController" like this.. Utils.showAlertOnVC(ViewController(), title: "title", message: "message") still getting the same error :/ – Akshay Kheveria Jul 13 '15 at 01:23
  • That's because that is wrong. Your code is creating a new instance of a view controller and passing that to the method. That's wrong. You should call my method from your view controller, and pass in self. – Duncan C Jul 13 '15 at 02:02