Swift4 - 错误域= NSCocoaErrorDomain代码= 4865

时间:2018-02-11 16:45:57

标签: php ios json swift

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响应保存到'user'类中,这样我就可以使用变量将数据插入到sql数据库中。我目前遇到的问题是错误消息......

“Error Domain = NSCocoaErrorDomain Code = 4865”没有与关键用户标识(“userid”)关联的值。“UserInfo = {NSCodingPath =( ),NSDebugDescription =没有与关键用户标识(“userid”)相关联的值。}“

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

{"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

1 个答案:

答案 0 :(得分:2)

正如您已经提到的那样,您的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