Friday 15 August 2014

ios - Parsing JSON array in swift -



ios - Parsing JSON array in swift -

i trying parse next json

[ { "id": "5", "name": "test", "team1": "thingy team", "team2": "clicky team", "category": "4", "end_date": "1415217600", "cat_name": "new thingy", "team1_bets": 1, "team2_bets": 1 } ]

this json getting web services, , using next code parse it:

let urlasstring = "http://codespikestudios.com/betting_app/bet/get_events/4" //let urlasstring = "http://api.topcoder.com/v2/challenges?pagesize=2" allow url: nsurl = nsurl(string: urlasstring)! allow urlsession = nsurlsession.sharedsession() allow jsonquery = urlsession.datataskwithurl(url, completionhandler: { data, response, error -> void in if (error != nil) { println(error.localizeddescription) } var err: nserror? var jsonresult = nsjsonserialization.jsonobjectwithdata(data, options: nsjsonreadingoptions.mutablecontainers, error: &err) nsdictionary if (err != nil) { println("json error \(err!.localizeddescription)") } println(jsontime) }) jsonquery.resume()

i getting next error

the operation couldn’t completed. (nsurlerrordomain error -1005.) fatal error: unexpectedly found nil while unwrapping optional value

how can solve this?

your url returning next json -

[ { "id": "5", "name": "test", "team1": "thingy team", "team2": "clicky team", "category": "4", "end_date": "1415217600", "cat_name": "new thingy", "team1_bets": 1, "team2_bets": 1 } ]

the outermost square brackets indicate root object array, attempting cast result of json parse nsdictionary causes problems.

your code should -

let urlasstring = "http://codespikestudios.com/betting_app/bet/get_events/4" allow url: nsurl = nsurl(string: urlasstring)! allow urlsession = nsurlsession.sharedsession() allow jsonquery = urlsession.datataskwithurl(url, completionhandler: { data, response, error -> void in if (error != nil) { println(error.localizeddescription) } var err: nserror? var jsonresult = nsjsonserialization.jsonobjectwithdata(data, options: nsjsonreadingoptions.mutablecontainers, error: &err) nsarray? if (err != nil) { println("json error \(err!.localizeddescription)") } println(jsonresult!) }) jsonquery.resume()

ios json swift

No comments:

Post a Comment