简体   繁体   English

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

[英]I cannot get the AWS Cognito credentials of a user (swiftUI)

I have tried a couple of different things, and at this point I am stumped.我尝试了几种不同的方法,在这一点上我很困惑。 I simply want to be able to access the user's email to present it in a view.我只是希望能够访问用户的 email 以在视图中显示它。 However I have not been able to successfully present, much less retrieve, this information.然而,我无法成功地呈现,更不用说检索这些信息了。 Here are the two pieces of code I have tried with:这是我尝试过的两段代码:

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

and

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
}

Does anyone know why this is not working?有谁知道为什么这不起作用?

After sign in try this:登录后试试这个:

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

I've tried getting the user attributes using AWSMobileClient getUserAttributes with no success.我尝试使用AWSMobileClient getUserAttributes获取用户属性但没有成功。 Also tried using AWSCognitoIdentityPool getDetails With no success.还尝试使用AWSCognitoIdentityPool getDetails没有成功。 Might be an error from AWS Mobile Client, but we can still get attributes from the id token, as seen above.可能是 AWS 移动客户端的错误,但我们仍然可以从 id 令牌中获取属性,如上所示。

If you are using Hosted UI, remember to give your hosted UI the correct scopes, for example:如果您使用的是托管 UI,请记住为您的托管 UI 提供正确的范围,例如:

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

It is because it is an async function so will return but later than when the function actually ends with the value.这是因为它是一个异步 function 所以会返回但晚于 function 实际以该值结束的时间。 Only way I found to do it is placing a while loop and then using an if condition.我发现这样做的唯一方法是放置一个 while 循环,然后使用 if 条件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM