我正在尝试发出一个POST请求,我之前只使用过字符串。这一次,我有一些变量:String
,Int
和Bool
。
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字节)
这是可选的导致问题吗?我该如何解决?
答案 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")
这可能就是为什么它不理解我发送它的字典