我做了一個使用CloudKit中的記錄的身份驗證,因此我創建了一個帳戶,然後進入我的登錄頁面並嘗試登錄,第一次按登錄時,它顯示我的錯誤消息「用戶名或密碼不正確「,但是第二次按下登錄按鈕時,它就起作用了。我真的不知道這是什麼原因造成的。CloudKit,我的身份驗證不工作
以下是我認爲是相關代碼:
func loginPressed() {
validLogin()
if usernameExists == true && passwordIsValid == true {
performSegue(withIdentifier: "loginToGames", sender: self)
} else {
self.incorrectLabel.isHidden = false
}
}
func validLogin() {
let container = CKContainer.default()
let pubDB = container.publicCloudDatabase
//query users to find current user
let query = CKQuery(recordType: "MyUsers", predicate: Predicate(format: "TRUEPREDICATE", argumentArray: nil))
pubDB.perform(query, inZoneWith: nil, completionHandler: { (records, error) in
if error == nil {
for record in records! {
if record.object(forKey: "Username") as? String == self.usernameField.text {
self.incorrectLabel.isHidden = true
self.usernameExists = true
print("searchUsername \(record.object(forKey: "Username") as? String)")
} else {
self.incorrectLabel.isHidden = false
self.usernameExists = false
print("searchUsername error")
}
}
} else {
print("searchLoginError\(error)")
}
})
let queryPassword = CKQuery(recordType: "MyUsers", predicate: Predicate(format: "TRUEPREDICATE", argumentArray: nil))
pubDB.perform(queryPassword, inZoneWith: nil, completionHandler: { (records, error) in
if error == nil {
for record in records! {
if record.object(forKey: "Password") as? String == self.passwordField.text {
self.incorrectLabel.isHidden = true
self.passwordIsValid = true
print("searchPassword \(record.object(forKey: "Password") as? String)")
} else {
self.incorrectLabel.isHidden = false
self.passwordIsValid = false
print("searchPassword error")
}
}
} else {
print("searcherror\(error)")
}
})
}
func checkValidLogin() {
let container = CKContainer.default()
let pubDB = container.publicCloudDatabase
//query users to find current user
let query = CKQuery(recordType: "MyUsers", predicate: Predicate(format: "TRUEPREDICATE", argumentArray: nil))
pubDB.perform(query, inZoneWith: nil, completionHandler: { (records, error) in
//we do not need to check for error code 11 because a user should exist
if error == nil {
var userExists = false
for record in records! {
if record.object(forKey: "Username") as? String == self.usernameField.text {
if record.object(forKey: "Password") as? String == self.passwordField.text {
OperationQueue.main.addOperation {
userExists = true
UserDefaults.standard.set(self.usernameField.text!, forKey: "Username")
username = self.usernameField.text!
}
} else {
//user with the username exists, but the password does not match
self.incorrectLabel.isHidden = false
}
}
}
if userExists == false {
//user with that username does not exist
self.incorrectLabel.isHidden = false
}
} else {
print("searcherror \(error)")
}
})
}
對不起,該在哪裏添加?我是編碼新手。 – RufusV