简体   繁体   中英

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. 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. Also tried using AWSCognitoIdentityPool getDetails With no success. Might be an error from AWS Mobile Client, but we can still get attributes from the id token, as seen above.

If you are using Hosted UI, remember to give your hosted UI the correct scopes, for example:

 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. Only way I found to do it is placing a while loop and then using an if condition.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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