gpt4 book ai didi

php - Swift4 - 错误域=NSCocoaErrorDomain 代码=4865

转载 作者:搜寻专家 更新时间:2023-11-01 07:04:43 25 4
gpt4 key购买 nike

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()
}

所以目标是将 JSON 响应保存到“用户”类中,这样我就可以使用变量将数据插入到 sql 数据库中。我目前遇到的问题是错误消息...

"Error Domain=NSCocoaErrorDomain Code=4865 "没有与 key 用户 ID ("userid") 关联的值。"UserInfo={NSCodingPath=(), NSDebugDescription=没有与键 userid ("userid") 关联的值。}"

我觉得问题是 HTTP 响应以数组形式返回数据,然后无法解码(下面列出的 HTTP 响应是我一直用于测试目的的 responseString)

{"user":{"userid":2,"sfname":"John","slname":"Doe","email":"john@doe.com","sid":123456}}

这是用于返回数据的 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;
}

提前致谢:D

最佳答案

正如您自己提到的,您的 JSON 结构与您的 user 结构不匹配。

您可以做两件事:尝试弄清楚为什么返回的 JSON 被包装在另一个 JSON 对象中,或者您创建一个与接收到的 JSON 结构相匹配的包装器结构。

第二种方法的结果应该是这样的:

struct UserWrapper: Decodable {
let user:user
}

然后当您从 JSON 简单地创建您的用户时

let wrapper = try JSONDecoder().decode(UserWrapper.self, from: data)
myStruct = wrapper.user

顺便说一句:我建议您阅读 Swift 风格指南。按照约定,函数名称应以小写字母开头,类/结构名称应以大写字母开头。函数中的命名参数也是记录代码的一件很酷的事情。

有点像

func doLogin(userWithMail email: String, andPassword password: String) {...}
// ... other stuff
// call
doLogin(userWithMail: "test@test.com", andPassword: "1234567")

可以更具可读性。以防万一您将来必须共享您的代码库。 ;D

关于php - Swift4 - 错误域=NSCocoaErrorDomain 代码=4865,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48733870/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com