My function getWeatherInfo()
retrieves data from a weather web service, parses the json, and sorts certain information into my array, info
. After I set up my function, I ran the program and got this error: The operation couldn’t be completed. (NSURLErrorDomain error -1005.)
fatal error: unexpectedly found nil while unwrapping an Optional value. It tells me this error when I declare my variable jsonResult
Here's the code:
var info = [AppModel]()
func getWeatherInfo(completion: (results : NSArray?) ->Void){
let urlPath = "http://api.openweathermap.org/data/2.5/weather?zip=92606,us&units=imperial"
let url: NSURL = NSURL(string: urlPath)!
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithURL(url, completionHandler: {data, response, error -> Void in
if error != nil {
// If there is an error in the web request, print it to the console
println(error.localizedDescription)
}
var err: NSError?
var jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &err) as NSDictionary // here is where I recieve my error
if err != nil {
// If there is an error parsing JSON, print it to the console
println("JSON Error \(err!.localizedDescription)")
}
let json = JSON(jsonResult)
var temp = json["main"]["temp"].stringValue
var humidity = json["main"]["humidity"].stringValue
var pressure = json["main"]["pressure"].stringValue
var information = AppModel(temperature: temp, pressure: pressure, humidity: humidity)
println(information)
self.info.append(information)
completion(results: self.info)
})
task.resume()
}
override func viewDidLoad() {
super.viewDidLoad()
getWeatherInfo{ (info) in
println(info)
}
}
It's been working fine before in the past, and I was successfully get the data back from the web service and sort information into my array. Can someone point me in the right direction on how I can fix this?