I keep getting an error when I try to send JSON data to the site. But when I check the site, I see that all the data in json has been sent and is correct.
The error I am getting is:
Error: Error Domain=NSCocoaErrorDomain Code=3840 "JSON text did not start with array or object and option to allow fragments not set." UserInfo={NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}
The code I have is:
let json = [ "name": "john", "last name": "smith" ] do{ let jsonData = try NSJSONSerialization.dataWithJSONObject(json, options: .PrettyPrinted) let url = NSURL(string: website) let request = NSMutableURLRequest(URL: url!) request.HTTPMethod = "POST" request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type") request.HTTPBody = jsonData let task = NSURLSession.sharedSession().dataTaskWithRequest(request){ data, response, error in if error != nil{ print("Error: \(error)") return } do { let result = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? [String:AnyObject] print("Result: \(result)") } catch { print("Error: \(error)") } } task.resume() } catch { print(error) }
When I admit fragments:
try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments)
I get another error:
Error: Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0." UserInfo={NSDebugDescription=Invalid value around character 0.}
I changed:
try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments)
to
try NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions.AllowFragments)
and I no longer get the error message.
source share