2017-02-09 172 views
0

我很难捕获Cognito注册错误。当Cognito返回“UsernameExistsException”,“message”:“用户已经存在”错误时,我试图提醒用户。 下面是我的代码:AWS Cognito:试图提醒错误用户

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 =零条件语句!当我强制执行错误时,错误不会打印,并且警报操作不会显示在视图中。我是否试图以错误的功能提醒用户?如何检查用户名已存在由cognito提供的错误。提前致谢。

回答

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

这种方法继续只临危回调,当一个错误发生就会被调用。