an new swift 2 , try write app in swift 2 makes http post request can't figure out how use new error handling of swift 2.am using try catch method still error shows "terminating app due uncaught exception 'nsinvalidargumentexception', reason: '*** +[nsjsonserialization datawithjsonobject:options:error:]: invalid top-level type in json write"
here code works in swift 1.2
//post request json var request = nsmutableurlrequest(url: nsurl(string: url)!) var session = nsurlsession.sharedsession() request.httpmethod = "post" var jsonstring = "{\"authentication\":{\"username\":\"test\",\"password\":\"test\"},\"requesttype\":4}" var err: nserror? request.httpbody = jsonstring.datausingencoding(nsutf8stringencoding, allowlossyconversion: true) 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) print("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)'") //postcompleted(succeeded: false, msg: "error") } 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 let success = parsejson["statuscode"]as? int if(success == 200) { println("success") } return } 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)") self.loadingindicator.stopanimating() } } }) task.resume()
and trying below code in swift 2
//post request json let request = nsmutableurlrequest(url: nsurl(string: url)!) let session = nsurlsession.sharedsession() let jsonstring : nsstring = "{\"authentication\":{\"username\":\"\(usernametextfield.text)\",\"password\":\"\(passwordtextfield.text)\"},\"requesttype\":7}" request.httpmethod = "post" //request.httpbody = jsonstring.datausingencoding(nsutf8stringencoding, allowlossyconversion: true) request.addvalue("application/json", forhttpheaderfield: "content-type") request.addvalue("application/json", forhttpheaderfield: "accept") { let param = jsonstring.datausingencoding(nsutf8stringencoding) request.httpbody = try nsjsonserialization.datawithjsonobject(param!, options: []) } catch { print(error) request.httpbody = nil } let task = session.datataskwithrequest(request, completionhandler: {data, response, error -> void in // handle error guard error == nil else { return } print("response: \(response)") let strdata = nsstring(data: data!, encoding: nsutf8stringencoding) print("body: \(strdata)") let json: nsdictionary? { json = try nsjsonserialization.jsonobjectwithdata(data!, options: .mutableleaves) as? nsdictionary } catch let dataerror { // did jsonobjectwithdata constructor return error? if so, log error console print(dataerror) let jsonstr = nsstring(data: data!, encoding: nsutf8stringencoding) print("error not parse json: '\(jsonstr)'") // return or throw? return } // 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 let success = parsejson["success"] as? int print("succes: \(success)") } else { // woa, okay json object nil, went worng. maybe server isn't running? let jsonstr = nsstring(data: data!, encoding: nsutf8stringencoding) print("error not parse json: \(jsonstr)") } }) task.resume()
let param = jsonstring.datausingencoding(nsutf8stringencoding) request.httpbody = try nsjsonserialization.datawithjsonobject(param!, options: [])
here you're converting string nsdata
, feeding result datawithjsonobject
. sincerely doubt that's wanted :)
try instead:
request.httpbody = try nsjsonserialization.datawithjsonobject(jsonstring, options: [])
Comments
Post a Comment