ios - Why is my code crashing when I run it in Thread 6: NSOperationQueue? -


class viewcontroller: uiviewcontroller {      override func viewdidload() {         super.viewdidload()          let url = nsurl(string: "https://api.forecast.io/forecast/mykeyhere/")         let session = nsurlsession.sharedsession()         let task: nsurlsessiondownloadtask = session.downloadtaskwithurl(url!, completionhandler: { (location: nsurl!, response: nsurlresponse!, error: nserror!) -> void in             if error == nil {                 let data = nsdata(contentsofurl: location)                 let json: nsdictionary = nsjsonserialization.jsonobjectwithdata(data!, options: nil, error: nil) as! nsdictionary!                 println(json)             }         })         task.resume()      } 

this code download task weather api. wondering why getting error:

thread 6: exc_bad_instruction(code=exc_1386_invop, subcode=0x0).

thanks lot.

you're getting error because response not json (or json not dictionary). so, when parsing json, use optional binding gracefully handle nil or non-dictionary errors, perhaps examining body of response if fails, e.g.:

let task = session.downloadtaskwithurl(url!) { location, response, error in     if error == nil {         let data = nsdata(contentsofurl: location)         var error: nserror?         if let json = nsjsonserialization.jsonobjectwithdata(data!, options: nil, error: &error) as? nsdictionary {             println("json = \(json)")         } else {             println("error = \(error)")             let responsestring = nsstring(data: data!, encoding: nsutf8stringencoding)             println("not json; responsestring = \(responsestring)")             println(response)         }     } } task.resume() 

also, note, when using jsonobjectwithdata, not want gracefully check error, want use error parameter, too, noted above.

btw, make sure include latitude , longitude in url described in forecast.io api documentation, or else you'll non-json error response. if fix url avoid error, should still implement graceful handling of errors, above, or else app might crash whenever there server issues.


Comments

Popular posts from this blog

angularjs - ADAL JS Angular- WebAPI add a new role claim to the token -

php - CakePHP HttpSockets send array of paramms -

node.js - Using Node without global install -