Chris Allinson Chris Allinson - 1 month ago 36
JSON Question

POST w/ JSON Body - Swift3 - fragments?

I'm simply trying to send a JSON string via a Swift3 httprequest.

Tried using a Dictionary, and an escaped string ...

func getToken(successHandler: @escaping (Any) -> Void, errorHandler: @escaping (Any) -> Void) {

var request = URLRequest(url: URL(string: "http://my-api.domain.com/getToken")!)

request.httpMethod = "POST"

request.setValue("application/json", forHTTPHeaderField: "Content-Type")

do
{
// try with Dictionary
let bodyJson: [String: String] = [
"client_id": "wkwbvwoubvwovb",
"username": "12345",
"password": "abcde"
]
let bodyJsonData = try JSONSerialization.data(withJSONObject: bodyJson, options: [])

// try with escaped String
let jsonString = "{" +
"\"client_id\": \"wkwbvwoubvwovb\"," +
"\"username\": \"12345\"," +
"\"password\": \"abcde\"," +
"}"
let jsonStringData = jsonString.data(using: String.Encoding.utf8)


//request.httpBody = bodyJsonData
request.httpBody = jsonStringData


let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard error == nil else {
print(error)
errorHandler(error)
return
}
guard let data = data else {
print("Data is empty")
errorHandler("Data is empty")
return
}

var json: Any? = nil
do
{
json = try JSONSerialization.jsonObject(with: data, options: [])

DispatchQueue.main.asyncAfter(deadline: .now()) {
successHandler(json)
}
}
catch let error as NSError {
errorHandler(error)
}
}

task.resume()
}
catch
{
errorHandler(error)
}
}


I keep getting:


Handle 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.}


I can't find how to try allowing fragments, all of the examples/tutorials are for Swift2.x :/

Unsure what to do!

Answer
// prepare json data
  let mapDict = [ "1":"First", "2":"Second"]

  let json = [ "title":"ABC" , "dict": mapDict ] as [String : Any]

  do {
     let jsonData = try JSONSerialization.data(withJSONObject: json, options: .prettyPrinted)

     // create post request
     let endpoint: String = "https://yourAPI"
     let session = URLSession.shared
     let url = NSURL(string: endpoint)!
     let request = NSMutableURLRequest(url: url as URL)
     request.httpMethod = "POST"

     // insert json data to the request
     request.httpBody = jsonData


     let task = session.dataTask(with: request as URLRequest){ data,response,error in
        if error != nil{
           print(error?.localizedDescription)
           return
        }
     }
     task.resume()
  } catch {
     print("bad things happened")
  }
Comments