0

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?

videoperson
  • 139
  • 1
  • 12
  • So explain what changed. Did you switch to Xcode 7? Did you switch to iOS 9? What? – matt Sep 29 '15 at 02:26
  • The only changes I made was the code I added to viewDidLoad(), the `getWeatherInfo{ (info) in println(info) }` Other than that, nothing. – videoperson Sep 29 '15 at 02:30

1 Answers1

1

Occasional network problems are normal. Wait a while and try again. The mistake in your code is here:

        if error != nil {
            println(error.localizedDescription)
        }

Should be:

        if error != nil {
            println(error.localizedDescription)
            return
        }

If there is an error you must stop, or you'll also crash.

matt
  • 515,959
  • 87
  • 875
  • 1,141