Presenting a UIAlertController from a class?

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

  1. bitfactory macrumors 6502

    bitfactory

    Joined:
    Jul 22, 2002
    #1
    Hi.

    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:

    Code:
    let alertController = UIAlertController(title: "Error", message: "Error message to go here.", preferredStyle: .Alert)                        
    
    let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel) { (action) in
    println(action)                        
    }
    alertController.addAction(cancelAction)
    
    let destroyAction = UIAlertAction(title: "Delete", style: .Destructive) { (action) in
    // my action is here
    }
    
    alertController.addAction(destroyAction)
    
    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

    Code:
    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...

    Code:
    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.

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

    Any ideas?

    Thanks!
     
  2. PhoneyDeveloper macrumors 68030

    PhoneyDeveloper

    Joined:
    Sep 2, 2008
    #2
    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

    bitfactory

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

Share This Page