Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS Build a Weather App with Swift Refreshing the Data The End

Where should i introduce the UIAlert code?

i was trying to introduce this code in my switch statement but the self.presentViewController doesn`t work in my network operation class, only in the view controller

func creatingAnAlert(){
        let alert = UIAlertController(title: "alert", message: "network error", preferredStyle: UIAlertControllerStyle.Alert)
        alert.addAction(UIAlertAction(title: "ok", style: UIAlertActionStyle.Default, handler: nil))

    self.presentViewController(alert, animated: true, completion: nil)
    }

1 Answer

Dominic Bryan
Dominic Bryan
14,452 Points

I am slightly unclear as to what your "network operation class" is, but I assume it is a class in another .swift file where you do some network operation which you call in your view controller.

In that case then the problem with your code is the

self.presentViewController(alert, animated: true, completion: nil)

Using

self.

tries to present the alert controller in the network operations class. I would suggest that in your network operations class you have a completion block, or error block so in your view controller, upon calling the network operation you can call the

creatingAnAlert()

function in the completion block.

i improved my method with a completion handler and created an instance on the view controller, so i was able to use the self.presentViewController method.However when i run the app, the debug area shows this message:Warning: Attempt to present <UIAlertController: 0x7f8cba5b94d0> on <Stormy.ViewController: 0x7f8cba443900> whose view is not in the window hierarchy!

i was able to create an alert but i donΒ΄t know how to introduce it when the network fails, do you know how can i do that?