如何使用不同的对象发出此POST请求?

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

Overview:

我正在尝试发出一个POST请求,我之前只使用字符串。这一次,我有一些变量,分别是:StringIntBool

Error:

Cannot assign value of type [String : Any] to type Data

Line causing the error:

request.httpBody = paramToSend

Question:

  • 如何将Dictionary转换成Data

Complete Code:

func sendComplimentAPI (message: String, recipient: Int, isPublic: Bool) {
    let url = URL(string: "https://complimentsapi.herokuapp.com/compliments/send/")
    let session = URLSession.shared
    let preferences = UserDefaults.standard
    let request = NSMutableURLRequest(url: url!)
    request.addValue("\(preferences.object(forKey: "token") as! String)", forHTTPHeaderField: "Authorization")
    request.httpMethod = "POST"

    let paramToSend = ["message":message,"recipient":recipient,"is_public":isPublic] as [String : Any] 
    request.httpBody = paramToSend

    let task = session.dataTask(with: request as URLRequest, completionHandler: {
        (data, response, error) in

        guard let _:Data = data else {return}
        let json:Any?
        do{json = try JSONSerialization.jsonObject(with: data!, options: [])}
        catch {return}

        guard let server_response = json as? NSDictionary else {return}

        if let session_data = server_response["id"] as? String {

            print("worked")
           //do something
            /*DispatchQueue.main.async (
                execute:
            )*/
        } else {
            print("error")
        }
    })

    task.resume()

}

编辑:

我尝试过这个新代码,但仍未发布到服务器上。我附加了我改变的内容,并且还编写了控制台为我所做的两个打印件显示的内容。

let paramToSend = ["message":writeTextField.text!,"recipient":1,"is_public":isPrivate] as [String : Any] //messageString + recipientString + isPublicString

            do {
                var serialized = try JSONSerialization.data(withJSONObject: paramToSend, options: .prettyPrinted)
                print(serialized)
                request.httpBody = serialized
                print(request.httpBody)
            } catch {
                print("found a problem")
            }

控制台返回(对于序列化,然后是HTTP正文):113字节可选(113字节)

这是可选的导致问题吗?我如何解决它?

json swift post
2个回答
0
投票

要将Dictionary转换为Data,请使用JSONSerialization.data

Solution:

JSONSerialization.data(withJSONObject: paramToSend, options: .prettyPrinted)

Check the request:

  • 打印请求,看看它是否符合您的期望

Reading the response:

//Check if there is any error (check if error != nil)

//Examine the response
let statusCode = (response as? HTTPURLResponse)?.statusCode
let statusCodeDescription = (response as? HTTPURLResponse)?.localizedString(forStatusCode: httpResponse.statusCode)

//Check Data
if let data = data {
    let dataString = String(data: data, encoding: String.Encoding.utf8)
}

0
投票

事实证明我需要添加一个简单的附加标题来使整个过程发挥作用。

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

这可能是为什么它不理解我发送它的字典

© www.soinside.com 2019 - 2024. All rights reserved.