Swift-将NSDictionary作为POST中的参数发送

问题描述 投票:0回答:1

我能够在POSTMAN中成功发出这样的POST请求:

{
  "id": "1",
  "myDictKey": {
    "key0": "blah",
    "key1": "blah",
    "key2": "blah"
  } 
}

但是,当我尝试快速发出此POST请求时,POST失败。 NSDictionary参数似乎没有得到预期的编码。

Swift Code

    let dictParam = ["key0": "blah", "key1": "blah", "key2": "blah"] as NSDictionary
    let urlString = MY_URL
    let url = URL(string: urlString)!
    var request = URLRequest(url: url)
    request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
    request.httpMethod = "POST"
    let parameters: [String: Any] = [
        "id": "1",
        "myDictKey": dictParam
    ]

    request.httpBody = parameters.percentEncoded()

     let task = URLSession.shared.dataTask(with: request) { data, response, error -> Void in
        if error != nil {
            completion(nil, error?.localizedDescription)
            return
        }

        do {
            if let json = try JSONSerialization.jsonObject(with: data!, options: [.allowFragments]) as? NSDictionary {
                if response?.statusCode() == 200 {
                    if let jsonResponse = json.value(forKeyPath: "response") as? NSDictionary {
                            completion(jsonResponse, nil)
                            return

                } else if response?.statusCode() == 401 {
                    completion(nil, "Unauthorized")
                } else {
                    completion(nil, "Something went wrong. Try again later")
                }
            }
        } catch {
            completion(nil, "Something went wrong. Try again later")
        }
    }
    task.resume()
ios swift nsurlconnection
1个回答
0
投票

您需要的是JSONSerialize参数:

request.httpBody = try? JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted)
© www.soinside.com 2019 - 2024. All rights reserved.