我难以捕获Cognito Sign Up Error。当Cognito返回“UsernameExistsException”,“message”:“User already exists”错误时,我正在尝试提醒用户。 以下是我的代码:
self.pool!.signUp(usernameTextField.text!, password: passwordTextField.text!, userAttributes: attributes, validationData: nil).continue(successBlock: { (task:AWSTask!) in
// needs to be async so we can ALWAYS return nil for AWSTask
DispatchQueue.main.async {
if task.error != nil { // some sort of error
let myerror = task.error
print("\(myerror)")
let alert = UIAlertController(title: "Sign Up Error", message: (task.error?.localizedDescription)! as String, preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
else {
let response: AWSCognitoIdentityUserPoolSignUpResponse = task.result! as AWSCognitoIdentityUserPoolSignUpResponse
// NSLog("AWSCognitoIdentityUserPoolSignUpResponse: \(response)")
self.user = response.user
let alert = UIAlertController(title: "Sign Up Successful", message: "", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: { action in self.performSegue(withIdentifier: "confrimationSegue", sender: self) }))
self.present(alert, animated: true, completion: nil)
}
}
return nil
})
由于某种原因,我无法进入task.error!= nil条件语句。当我强制执行错误时,错误不会打印,并且警报操作不会显示在视图中。我是否试图用错误的功能提醒用户?我怎样才能检查cognito提供的用户名已存在错误。提前谢谢。
答案 0 :(得分:1)
您正在使用successBlock
,这意味着只有在成功执行注册时才会调用您设置的块。这就是为什么错误总是nil
。
为了获得错误,您应该通过以下方式设置回调:
userPool
.signUp(user.email, password: user.password, userAttributes: attributes, validationData: nil)
.continue({ response in
if let error = response.error {
// Error ocurred
} else {
// No error ocurred
})
此continue方法仅接收回调,并在发生错误时调用。