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 trialIgor Alves
Courses Plus Student 4,115 Pointshelp displaying the alert!!
Here is my code of the networkOperation class, i have two problems: first my alert is not in the window hierarchy so it is giving me problems to dispay it and i dont know how to fix it,
the second is that i don
t know how can i retry the network operation
import Foundation
import UIKit
class networkOperation{
lazy var config:NSURLSessionConfiguration = NSURLSessionConfiguration.defaultSessionConfiguration()
lazy var session:NSURLSession = NSURLSession(configuration:self.config)
typealias JSONDictionaryCompletion = ([String:AnyObject]->Void)
let queryURL:NSURL
init(url:NSURL){
self.queryURL = url
}
func downloadJSONfromURL(completion:JSONDictionaryCompletion){
let request = NSURLRequest(URL: queryURL)
let dataTask = session.dataTaskWithRequest(request) {
(let data,let response, let error) in
// HTTP response eh uma reposta do servidor ao cliente quando recebe uma HTTP request.The response contains info about the date,size of the request and other things like the status code
//1:check HTTP response for sucessful GET request
if let httpResponse = response as? NSHTTPURLResponse{//casting pq NSHTTPPURLResponse tem method para os status code
switch(httpResponse.statusCode){
case 200:
//Create JSON object with data
let JSONDictionary = try!NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions()) as! [String:AnyObject]
completion(JSONDictionary)
//NSJSONSerialization->usada para converter JSON para foundation objects e foundation objects para JSON objects
case 400:
print("probably mispelled, please try again")
default:
print("bad request")
}}
else{
print("ERROR!!!!not valid http response")
self.creatingAnAlert{
(let errorAlert) in
let viewController = ViewController()
errorAlert.addAction(UIAlertAction(title: "retry", style: UIAlertActionStyle.Default, handler: //retry loading the weather data))
viewController.presentViewController(errorAlert, animated: true, completion: nil)
}
}
}
dataTask.resume()
}
func creatingAnAlert(handler: (UIAlertController)->Void){
let alert = UIAlertController(title: "Alert", message: "error", preferredStyle: .Alert)
alert.addAction(UIAlertAction(title: "ok", style: UIAlertActionStyle.Default, handler: nil))
handler(alert)
}
}