Vah*_*Sah 11 json ios nsurlsession swift
在我的应用程序中,我正在尝试使用json数据发出http post请求.以下json必须转移到api
{
"Password":"123456",
"Email":"test@gmail.com"
}
Run Code Online (Sandbox Code Playgroud)
这是我执行此任务的代码
let dict = ["Email": "test@gmail.com", "Password":"123456"] as [String: Any]
if let jsonData = try? JSONSerialization.data(withJSONObject: dict, options: []) {
let url = NSURL(string: "http://xxxxxxxxx.net/api/Login")!
let request = NSMutableURLRequest(url: url as URL)
request.httpMethod = "POST"
request.httpBody = jsonData
let task = URLSession.shared.dataTask(with: request as URLRequest){ data,response,error in
if error != nil{
print(error?.localizedDescription)
return
}
do {
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
if let parseJSON = json {
let resultValue:String = parseJSON["success"] as! String;
print("result: \(resultValue)")
print(parseJSON)
}
} catch let error as NSError {
print(error)
}
}
task.resume()
}
Run Code Online (Sandbox Code Playgroud)
我收到以下错误
Error Domain=NSCocoaErrorDomain Code=3840 "No value." UserInfo={NSDebugDescription=No value.}
Run Code Online (Sandbox Code Playgroud)
响应数据为空.我做错了什么,或者我在代码中遗漏了什么?
Sah*_*jan 19
尝试两件事:
第一:
jsonData = try? JSONSerialization.data(withJSONObject: dict, options: .prettyPrinted)
Run Code Online (Sandbox Code Playgroud)
如果您的数据转换为JSON,则添加日志.将数据转换为String并打印该值.
还添加
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
Run Code Online (Sandbox Code Playgroud)
之前httpBody
.有时我们必须在请求中告诉服务器我们正在发布JSON数据.
希望对你有帮助!!
快乐的编码!
归档时间: |
|
查看次数: |
19761 次 |
最近记录: |