【问题标题】:I cannot get the AWS Cognito credentials of a user (swiftUI)我无法获取用户的 AWS Cognito 凭证 (swiftUI)
【发布时间】:2020-06-06 22:00:14
【问题描述】:

我尝试了几种不同的方法,但在这一点上我很难过。我只是希望能够访问用户的电子邮件以将其呈现在视图中。但是,我无法成功呈现,更不用说检索这些信息了。这是我尝试过的两段代码:

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
}

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

【问题讨论】:

  • 成功登录后,我可以使用AWSCognitoIdentityUserPool.default().currentUser()?.username 获取 currentUser 用户名。但我无法获取其余属性.. 你成功了吗?

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


【解决方案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 移动客户端的错误,但我们仍然可以从 id 令牌中获取属性,如上所示。

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

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

【讨论】:

    【解决方案2】:

    这是因为它是一个异步函数,所以会返回但晚于函数实际以该值结束的时间。我发现这样做的唯一方法是放置一个 while 循环,然后使用 if 条件。

    【讨论】:

    • 这是评论,不是答案
    猜你喜欢
    • 2018-03-28
    • 2019-01-21
    • 2016-05-10
    • 2021-09-13
    • 2017-08-27
    • 1970-01-01
    • 1970-01-01
    • 2017-11-26
    • 1970-01-01
    相关资源
    最近更新 更多