Swift 2.0 String of JSON to JSON -
i'm working in swift 2.0 , struggling json. pulling json website in form of swift.optional<nsdata>
. can convert string using
if let x = nsstring(data: data!, encoding: nsutf8stringencoding){ let y = x string }
i'm trying json data dictionary in swift , struggling. what's best way this?
update
let task = nsurlsession.sharedsession().datataskwithurl(url!) {(data, response, error) in if let z = nsjsonserialization.jsonobjectwithdata(data!, options:[]) as? [nsobject: anyobject] { }
it errors with
- type of expression ambiguous without more context
- call can throw, not marked 'try' , error not handled
in swift 2, if function "throws" (as nsjsonserialization
does), have handle function call inside do ... catch
block , use try
before throwing function, this:
let task = nsurlsession.sharedsession().datataskwithurl(url!) {(data, response, error) in { let z = try nsjsonserialization.jsonobjectwithdata(data!, options:[]) as! [nsobject: anyobject] print(z) } catch let myjsonerror { print(myjsonerror) } } task!.resume()
note in example, possible nsjsonserialization
failure handled do...catch
, try
custom myjsonerror
error, possible failure of nsurlsession
not handled: still have check error
variable in order handle this. because nsjsonserialization
"throws" nsurlsession
not.
Comments
Post a Comment