ios - NSMutableURLRequest - HTTPBody from Swift Array -
i need send post request server httpbody of array. here's array of parameters:
params = [ "message" : [ "alert" : "find iphone", "sound" : "binocular_default.caf" ] ]
now need set nsmutableurlrequest
's httpbody
array. how can that?
create mutable request params. , try following code
var request = nsmutableurlrequest(url: nsurl(string: "yoururl")) var session = nsurlsession.sharedsession() request.httpmethod = "post" //create dictionary parameters var params = ["username":"test", "password":"pass"] dictionary<string, string> var err: nserror? request.httpbody = nsjsonserialization.datawithjsonobject(params, options: nil, error: &err) 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 // did jsonobjectwithdata constructor return error? if so, log error console if(err != nil) { println(err!.localizeddescription) } else { } }) task.resume()
Comments
Post a Comment