1

I'm trying to add a value to a JSON's body from swift (issue_id), I've search everywhere but it looks like nobody actually answer nor asked my question. I've also tried to add it to the params which is obviously failed.

body

I know how to add parameters and header, but I have no idea how to add a value to the body, here's the code

private func restAPI(path: String, method: String, params: [String: Any], callback: @escaping(_ result: [[String: Any]]) -> Void) {

    var url: String = ""

    if path == "/login" {
        let dict = dictConvert(dictionary: params)
        url = baseUrl + path + dict
    }
    else {
        url = baseUrl + path
    }

    guard let urlData = URL(string: url) else {
        callback([])
        return
    }

    print("===URL=== " + url)

    let request = NSMutableURLRequest(url: urlData)
    request.httpMethod = "POST"

    if let key = UserDefaults.standard.string(forKey: "auth-key") {
        print("===Authentication=== " + key)
        request.addValue(key, forHTTPHeaderField: "Authentication")
    }
    let task = URLSession.shared.dataTask(with: request as URLRequest, completionHandler:{ (data, _ , error) in

        if error == nil {
            do {
                let stringData = String(data: data!, encoding: String.Encoding.utf8) as String!
                print("Data === " + (stringData ?? "nil"))

                if let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSArray {

                    guard let jsonArray = json as? [[String: Any]] else {
                        callback([])
                        return
                    }

                    callback(jsonArray)

                }
                else if let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary {

                    guard let jsonArray = json as? [String: Any] else {
                        callback([])
                        return
                    }

                    callback([jsonArray])

                }
                else {
                    callback([])
                }

            }
            catch _ {
                callback([])
            }
        }
    })
    task.resume()
}
Nodoodle
  • 57
  • 2
  • 8

1 Answers1

1

You need to use request.httpBody which is of type Data and pass on the body

 let bodyDictionary: [String: Any] = ["key1": value1,
                                         "key2": value2]
  let requestBodyData = try? JSONSerialization.data(withJSONObject: bodyDictionary, options: [])
    request.httpBody = requestBodyData
Milan
  • 141
  • 4