Presenting a UIAlertController from a class?

Discussion in 'iOS Programming' started by bitfactory, Jul 9, 2015.

  1. bitfactory macrumors 6502


    Jul 22, 2002

    I'm attempting to present a UIAlertController from a class (an extension, actually), but I'm having trouble trying to reference the View I'm coming from to present it.

    In the class (in some if/let statements), I have all the pieces of the UIAlertController:

    let alertController = UIAlertController(title: "Error", message: "Error message to go here.", preferredStyle: .Alert)                        
    let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel) { (action) in
    let destroyAction = UIAlertAction(title: "Delete", style: .Destructive) { (action) in
    // my action is here
    self.presentViewController(alertController, animated: true, completion: nil)
    The problem is in the last line... obviously self.presentViewController isn't going to work. As a matter of fact, self.presentViewController isn't even valid since the class didn't even have a member that allowed that.

    So in an attempt to fix it, I declared a UIViewController in the class

    var targetView: UIViewController!
    which enabled the .presentViewController method - but how do I reference the original active view in order to present this?

    Currently I just have this...

    self.targetView.presentViewController(alertController, animated: true, completion: nil)
    The app crashes right now when it gets here (found nil while unwrapping Optional) - which is most likely due to the declared value.

    - network call using a class
    - in the network call class closure i'm trying to present this AlertViewController in MyViewController

    Any ideas?

  2. PhoneyDeveloper macrumors 68040


    Sep 2, 2008
    Either you pass in a valid view controller when this class is built or you return an error (NSError or something like that) to the caller and the caller displays the alert.
  3. bitfactory, Jul 9, 2015
    Last edited: Jul 10, 2015

    bitfactory thread starter macrumors 6502


    Jul 22, 2002
    Edit: NM - I moved it out of the class and into a VC. Probably better form anyway.

Share This Page