ios - Is there need for mapping in Swift -
i'm beginner swift coding, , i'm trying send post request json. there need use objectmapper convert model object mapping objects json, or enough use next code:
@ibaction func submitaction(sender: anyobject) { //declare parameter dictionary contains string key , value combination. var parameters = ["name": nametextfield.text, "password": passwordtextfield.text] dictionary<string, string> //create url nsurl let url = nsurl(string: "http://myservername.com/api") //change url //create session object var session = nsurlsession.sharedsession() //now create nsmutablerequest object using url object let request = nsmutableurlrequest(url: url!) request.httpmethod = "post" //set http method post var err: nserror? request.httpbody = nsjsonserialization.datawithjsonobject(parameters, options: nil, error: &err) // pass dictionary nsdata object , set request body request.addvalue("application/json", forhttpheaderfield: "content-type") request.addvalue("application/json", forhttpheaderfield: "accept") //create datatask using session object send data server 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 // 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 { // 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 success = parsejson["success"] as? int println("succes: \(success)") } 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() }
and easier way , less complicated?
Comments
Post a Comment