Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

bitfactory

macrumors 6502
Original poster
Jul 22, 2002
347
390
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!
 
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.
 
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.

Edit: NM - I moved it out of the class and into a VC. Probably better form anyway.
 
Last edited:
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.