ios - Network call fails due to unwrapping -
this code making network call forecast.io
. inside viewcontroller
have:
private let apikey = ""//my key override func viewdidload() { super.viewdidload() // additional setup after loading view, typically nib. let baseurl = nsurl(string: "https://api.forecast.io/forecast/\(apikey)") let forecasturl = nsurl(string: "37.8267,-122.423", relativetourl : baseurl) let sharedsession = nsurlsession.sharedsession() let downloadtask : nsurlsessiondownloadtask = sharedsession.downloadtaskwithurl(forecasturl!, completionhandler: { (location: nsurl!, response: nsurlresponse!, error: nserror!) -> void in if (error == nil) { let dataobject = nsdata(contentsofurl: location) let weatherdictionary : nsdictionary = nsjsonserialization.jsonobjectwithdata( dataobject!, options: nil, error: nil) as! nsdictionary } }) downloadtask.resume() }
i'm trying set data nsdictionary
able access it. have bug (green line) has weatherdictionary
:
fatal error: unexpectedly found nil while unwrapping optional value
i'm unwrapping dataobject
, problem?
you really, seriously, need out of habit of force-unwrapping. if whenever optional, use !
unwrap it, going forever hitting these problems.
here’s version of inner code checks optionals @ each turn:
let sharedsession = nsurlsession.sharedsession() let downloadtask = sharedsession.downloadtaskwithurl(forecasturl!) { location, response, error in if let error = error { // log error } else if let dataobject = nsdata(contentsofurl: location) { let weatherobj: anyobject? = nsjsonserialization.jsonobjectwithdata( dataobject, options: nil, error: nil) if let weatherdictionary = weatherobj as? nsdictionary { } else { // log error conversion of weather dictionary } } else { // log error dataobject } }
yes, longer , more annoying write (though, type inference go other way – don’t have explicitly type e.g. in callback, it’s clearer imo leave types off).
yes, know sure value won’t nil, it’s easier , cleaner force-unwrap (e.g. nsurl
– can pretty safe 1 long no user-input involved).
but until point don’t bash head against nil-value errors constantly, it’s better write code way.
once more comfortable handling optionals, explore other techniques write neater code.
you might want consider using stronger typing when processing json results, example, following:
if let weatherdictionary = weatherobj as? [string:anyobject]
and on when processing inside of dictionary. again, if trust forecast.io
give valid json data in right form, can skip step , force harder debug when writing code, , risk code blowing in production (as opposed failing gracefully) if ever corrupt data back.
Comments
Post a Comment