Reputation: 183
I got below error when try to post an url with a dictionary as param;
NSCocoaErrorDomain Code=3840 "Unable to convert data to string around character 34
And my code below;
func postOrder() {
let params = [
“date”: ”25.12.2015”,
“time” : “22:34”,
“order_no”: “23232322”,
"user_id" : “23232”
] as Dictionary<String, String>
let request = NSMutableURLRequest(URL: NSURL(string: "http://webservis.xxxxx.com/post_order.asp")!)
let session = NSURLSession.sharedSession()
request.HTTPMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
request.HTTPBody = try! NSJSONSerialization.dataWithJSONObject(params, options: [])
let task = session.dataTaskWithRequest(request) { data, response, error in
guard data != nil else {
print("no data found: \(error)")
return
}
let cfEnc = CFStringEncodings.ISOLatin5
let enc = CFStringConvertEncodingToNSStringEncoding(CFStringEncoding(cfEnc.rawValue))
let outputString = NSString(data: data!, encoding: enc)
do {
if let json = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary {
let success = json["success"] as? Int
print("Success: \(success)")
} else {
let cfEnc = CFStringEncodings.ISOLatin5
let enc = CFStringConvertEncodingToNSStringEncoding(CFStringEncoding(cfEnc.rawValue))
let jsonStr = NSString(data: data!, encoding: enc)
print("Error could not parse JSON: \(jsonStr)")
}
} catch let parseError {
print(parseError)
let cfEnc = CFStringEncodings.ISOLatin5
let enc = CFStringConvertEncodingToNSStringEncoding(CFStringEncoding(cfEnc.rawValue))
let jsonStr = NSString(data: data!, encoding: enc)
print("Error could not parse JSON: '\(jsonStr)'")
}
}
task.resume()
}
What is the problem on above code, can anybody help?
Upvotes: 0
Views: 1548
Reputation: 16813
Check that the data you're parsing is actually valid JSON (and not just 'nearly' JSON). That error is known to occur when you have a different data format that can't be parsed as JSON.
Replace your params
with the following and try again.
let params = [
"date": "25.12.2015",
"time" : "22:34",
"order_no": "23232322",
"user_id" : "23232"
] as Dictionary<String, String>
Furthermore, you may check the following thread iOS 5 JSON Parsing Results in Cocoa Error 3840
Upvotes: 0