[英]Swift4 - Error Domain=NSCocoaErrorDomain Code=4865
func DoLogin(_ email:String, _ password:String)
{
struct user : Decodable {
let userid: Int
let sfname: String
let slname: String
let email: String
let sid: Int
}
let url = URL(string: ".....")!
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!)
}
let responseString = String(data: data, encoding: .utf8)
print(responseString!)
do {
let myStruct = try JSONDecoder().decode(user.self, from: data)
print(myStruct)
} catch let error as NSError {
print(error)
}
}
task.resume()
}
So the aim is to save the JSON response into the 'user' class so i can use the variables to insert the data into an sql database. 因此,目标是将JSON响应保存到“用户”类中,以便我可以使用变量将数据插入sql数据库。 The problem I'm currently getting is the Error message...
我目前遇到的问题是错误消息...
"Error Domain=NSCocoaErrorDomain Code=4865 "No value associated with key userid ("userid")." UserInfo={NSCodingPath=( ), NSDebugDescription=No value associated with key userid ("userid").}" “错误域= NSCocoaErrorDomain代码= 4865”没有与键userid(“ userid”)关联的值。“ UserInfo = {NSCodingPath =(),NSDebugDescription =没有与键userid(” userid“)关联的值。}”
I feel the problem is that the HTTP response is returning the data back in an array form which is then not being able to be decoded (HTTP response listed below which is the responseString which I've been using for testing purposes) 我认为问题在于HTTP响应以数组形式返回数据,该数据随后无法被解码(下面列出的HTTP响应是我一直用于测试目的的responseString)
{"user":{"userid":2,"sfname":"John","slname":"Doe","email":"john@doe.com","sid":123456}}
Heres the PHP that is used to return the data. 这是用于返回数据的PHP。
public function getUserByEmail($email)
{
$stmt = $this->conn->prepare("SELECT userid, sfname, slname, email, sid FROM students WHERE email = ?");
$stmt->bind_param("s", $email);
$stmt->execute();
$stmt->bind_result($userid, $sfname, $slname, $email, $sid);
$stmt->fetch();
$user = array();
$user['userid'] = $userid;
$user['sfname'] = $sfname;
$user['slname'] = $slname;
$user['email'] = $email;
$user['sid'] = $sid;
return $user;
}
Thanks in advance :D 提前致谢
As you already mention yourself the structure of your JSON doesn't match the structure of your user
struct. 正如您已经提到的那样,JSON的结构与
user
结构的结构不匹配。
You could do two things: Try to figure out why the returned JSON is wrapped in another JSON object or you create a wrapper struct which matches the structure of the received JSON. 您可以做两件事:尝试弄清为什么将返回的JSON包装在另一个JSON对象中,或者创建一个与接收的JSON结构匹配的包装器结构。
The second approach should result in somethin like this: 第二种方法应产生如下结果:
struct UserWrapper: Decodable {
let user:user
}
Then when your create your user from the JSON simply to this 然后,当您从JSON创建用户时,只需
let wrapper = try JSONDecoder().decode(UserWrapper.self, from: data)
myStruct = wrapper.user
By the way: I would recommend you to read a Swift style guide. 顺便说一句:我建议您阅读Swift风格指南。 By convention function names should start with lowercases and class/struct names with uppercases.
按照约定,函数名称应以小写字母开头,而类/结构名称应以大写字母开头。 Also named parameters in functions are a very cool thing to document your code.
在函数中也命名为参数的文档是很酷的事情。
Something like 就像是
func doLogin(userWithMail email: String, andPassword password: String) {...}
// ... other stuff
// call
doLogin(userWithMail: "test@test.com", andPassword: "1234567")
could be more readable. 可能更具可读性。 Just in case you have to share your codebase in the future.
以防万一您将来必须共享您的代码库。 ;D
; d
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.