func DoLogin(_ email:String, _ password:String)
{
struct User: Decodable {
let sfname: String
let slname: String
let email: String
let sid: Int
}
let url = URL(string: "http://URL")!
var request = URLRequest(url: url)
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.httpMethod = "POST"
let postString = "email=" + email + "&password=" + password + ""
request.httpBody = postString.data(using: .utf8)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else { // check for fundamental networking error
print(error!)
return
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 { // check for http errors
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print(response!)
}
if let responseString = String(data: data, encoding: .utf8){
let myStruct = try JSONDecoder().decode(User.self, from: responseString)
}
}
task.resume()
}
所以目的是解码HTTP响应responseString
以便将信息保存到User
的属性中,但是在按顺序插入代码行后,我仍然会弹出相同的错误解码HTTP响应(myStruct
)。我觉得它与Do Try Catch错误处理有关,但无法解决这个问题。
提前感谢您的帮助:)
答案 0 :(得分:6)
这是你的问题:
let myStruct = try JSONDecoder().decode(User.self, from: responseString)
的完成处理程序
URLSession.shared.dataTask(with: URLRequest, completionHandler: (Data?, URLResponse?, Error?) -> Void)
不允许抛出或重新抛出异常。如果有的话,签名将是这样的:
URLSession.shared.dataTask(with: URLRequest, completionHandler: (Data?, URLResponse?, Error?) throws -> Void)
(请注意方法签名中的throws
)
此外,您需要确保将responseString
更改为data
。 decode
方法需要Data
个对象,而不是String
。实际上根本不需要将data
转换为String
,因此您可以从代码中删除此if
语句:
if let responseString = String(data: data, encoding: .utf8)
尝试做这样的事情:
do {
let myStruct = try JSONDecoder().decode(User.self, from: data)
//do something with myStruct
} catch let error as NSError {
//do something with error
}
或者这个:
if let myStruct = try? JSONDecoder().decode(User.self, from: data) {
//do something with myStruct
} else {
//handle myStruct being nil
}