我无法获取用户的AWS Cognito凭证(swiftUI)

时间:2020-02-22 19:50:06

标签: swift amazon-web-services swiftui amazon-cognito aws-amplify

我尝试了几种不同的方法,但现在我很沮丧。我只是希望能够访问用户的电子邮件以在视图中显示它。但是,我无法成功呈现(更不用说检索)此信息了。这是我尝试过的两段代码:

func getUsername() -> String? {
     if(self.isAuth) {
         return AWSMobileClient.default().username
     } else {
         return nil
     }
}

func getUserEmail() -> String {
     var returnValue = String()
     AWSMobileClient.default().getUserAttributes { (attributes, error) in
          if(error != nil){
             print("ERROR: \(String(describing: error))")
          }else{
             if let attributesDict = attributes{
                 //print(attributesDict["email"])
                 self.name = attributesDict["name"]!
                 returnValue = attributesDict["name"]!
             }
         }
    }
    print("return value: \(returnValue)")
    return returnValue
}

有人知道为什么这不起作用吗?

1 个答案:

答案 0 :(得分:1)

登录后,请尝试以下操作:

AWSMobileClient.default().getTokens { (tokens, error) in
                    if let error = error {
                        print("error \(error)")
                    } else if let tokens = tokens {

                        let claims = tokens.idToken?.claims
                        print("claims \(claims)")
                        print("email? \(claims?["email"] as? String ?? "No email")")
                    }
                }

我尝试使用AWSMobileClient getUserAttributes获取用户属性,但没有成功。还尝试使用AWSCognitoIdentityPool getDetails,但未成功。可能是来自AWS Mobile Client的错误,但是我们仍然可以从id令牌中获取属性,如上所述。

如果您使用的是托管用户界面,请记住为托管用户界面提供正确的范围,例如:

 let hostedUIOptions = HostedUIOptions(scopes: ["openid", "email", "profile"], identityProvider: "Google")