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

时间:2018-06-16 00:54:30

标签: json swift post

概述:

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

错误:

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

导致错误的行:

request.httpBody = paramToSend

问题:

  • 如何将Dictionary转换为Data

完整代码:

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字节)

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

2 个答案:

答案 0 :(得分:0)

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

解决方案:

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

检查请求:

  • 打印请求并查看其是否符合您的预期

阅读回复:

//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)
}

答案 1 :(得分:0)

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

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

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