该方法工作正常,它在后端执行我想要的操作,但我在控制台中收到以下错误:
错误域= NSCocoaErrorDomain代码= 3840“没有值。” UserInfo = {NSDebugDescription =无值。}
上述错误包含在catch
。
我读出了类似的问题,建议为标题增加价值,但也没有修复它。
let serverURL = URL(string: "https://xxx/xxx/xxx/xxx/xxx/email")
self.request = URLRequest(url:serverURL!)
self.request?.httpMethod = "POST"
self.request?.addValue("application/json", forHTTPHeaderField: "content-type")
self.request?.addValue("application/json", forHTTPHeaderField: "Accept")
do {
self.request?.httpBody = try JSONSerialization.data(withJSONObject: postContent, options: .prettyPrinted)
} catch let error {
print(error.localizedDescription)
return
}
json的格式为:postContent: [String: String]
,["email": "myemail@domain.com"]
任务代码:
let task = URLSession.shared.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in
if (self.activityIndicator != nil) {
self.removeActivityIndicator(activityIndicator: self.activityIndicator!)
}
guard let data = data else {return}
do {
let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String:String]
if let parseJSON = json {
self.alertMessage(message: "Please check your email for instructions.")
}
} else {
self.alertMessage(message: "Invalid email address!")
}
} catch {
self.alertMessage(message: "Could not send request. Try again!")
print(error)
}
}
task.resume()
答案 0 :(得分:0)
我认为你有一个拼写错误。你有没有尝试改变
self.request?.addValue("application/json", forHTTPHeaderField: "content-type")
到
self.request?.addValue("application/json", forHTTPHeaderField: "Content-Type")
答案 1 :(得分:0)
我得到了200
好的回复,但是json的身体被空了:
let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String:String]
我修改了API并添加了主体以响应以修复此问题。