javascript - Parse an Array of objects and populate table view cells Swift -
i have app trying pull in data api created ( api based on node.js, mongodb, express.js )
currently trying pull , array of objects , create tableview based on array of objects. example if array of objects contains 4 objects, table view have 4 cells. , on clicking cell go view able view detailed view of object.
how can parse returned json data api , populate table view cells?
my issue:
currently unable parse returned array of objects. below image of returned json contains:
the error:
i getting following error:
error not parse json: optional([ { "_id": "55d1db984f80687875e43f89", "password": "$2a$08$oqb/r9iizdsfln9l5vaie.qilb8gp/ytlsa3s41usvnm/exhbw9j6", "email": "syed.kazmi26@gmail.com", "__v": 0, "sector": "manufacturing", "jobtitle": "something 1", "employeename": "something 1" }, // displays data being returned in json response ])
below swift code:
import uikit class sectorviewcontroller: uiviewcontroller { @ibaction func getmanufacturingbios(sender: anyobject) { var request = nsmutableurlrequest(url: nsurl(string: "https://myurl/user/all")!) var session = nsurlsession.sharedsession() request.httpmethod = "get" uiapplication.sharedapplication().networkactivityindicatorvisible = true var err: nserror? request.addvalue("application/json", forhttpheaderfield: "content-type") request.addvalue("application/json", forhttpheaderfield: "accept") var task = session.datataskwithrequest(request, completionhandler: {data, response, error -> void in println("response: \(response)") var strdata = nsstring(data: data, encoding: nsutf8stringencoding) println("body: \(strdata)") var err: nserror? var json = nsjsonserialization.jsonobjectwithdata(data, options: .mutableleaves, error: &err) as? nsdictionary uiapplication.sharedapplication().networkactivityindicatorvisible = true // did jsonobjectwithdata constructor return error? if so, log error console if(err != nil) { println(err!.localizeddescription) let jsonstr = nsstring(data: data, encoding: nsutf8stringencoding) println("error not parse json: '\(jsonstr)'") } else { uiapplication.sharedapplication().networkactivityindicatorvisible = false // jsonobjectwithdata constructor didn't return error. but, should still // check , make sure json has value using optional binding. if let parsejson = json { // okay, parsedjson here, let's value 'success' out of var sector = parsejson["sector"] as! string println("succes: \(sector)") } else { // woa, okay json object nil, went worng. maybe server isn't running? let jsonstr = nsstring(data: data, encoding: nsutf8stringencoding) println("error not parse json: \(jsonstr)") } } }) task.resume() } }
maybe try use nsarray instead of dictionary , change reading options. recommend sth. this:
var json : nsarray? = nil json = (nsjsonserialization.jsonobjectwithdata(data, options:nsjsonreadingoptions.mutablecontainers , error: &error) as? nsarray)!
hope solves problem.
Comments
Post a Comment