2017-02-09 98 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 
     }) 

這種方法繼續只臨危回調,當一個錯誤發生就會被調用。