Nikita Zernov
Nikita Zernov

Reputation: 5635

How to get AWS Cognito user attributes using AWSMobileClient in iOS?

Question is very simple: I've added user authentication to iOS app using AWS Cognito and AWS Amplify. I have successfully implemented sign in and sign up, but how to get user attributes such as email, full name or phone number?

Upvotes: 3

Views: 5087

Answers (5)

Rohan Dubal
Rohan Dubal

Reputation: 847

You can use the getUserAttributes with the following API in the latest SDK version 2.8.x:

public func getUserAttributes(completionHandler: @escaping (([String: String]?, Error?) -> Void))

You can find the source code here:

https://github.com/aws-amplify/aws-sdk-ios/blob/master/AWSAuthSDK/Sources/AWSMobileClient/AWSMobileClientExtensions.swift#L532

Upvotes: 3

velociraptor11
velociraptor11

Reputation: 604

UPDATE:

For AWSMobileClient ~> 2.12.0, you can fetch user attributes as follows.

AWSMobileClient.default().getUserAttributes { (attributes, error) in
     if(error != nil){
        print("ERROR: \(error)")
     }else{
        if let attributesDict = attributes{
           print(attributesDict["email"])
           print(attributesDict["given_name"])
        }
     }
}

Upvotes: 7

Kome
Kome

Reputation: 56

I also research it on android (Kotlin).

// retrieve username
val username = AWSMobileClient.sharedInstance().username

When you sign in with "email" and "password", "username" is "email".

On the other hand, when the case of iOS (Swift), "username" is really "username" of cognito User Pool, even if you sign in with "email" and "password".

It is so confusing...

Upvotes: 0

Zig
Zig

Reputation: 2603

In case you're looking for the email address specifically, and need to do so potentially offline, this would work for you:

AWSMobileClient.sharedInstance().getTokens { (tokens, error) in
    if let error = error { print(error.localizedDescription) }
    if let tokens = tokens {
        let email = tokens.idToken?.claims?["email"] as? String
        //completionHandler(email)... etc.
    }

While AWSMobileClient.sharedInstance().getUsername() would be convenient, it will return the id of a User Pool user even if the User Pool is set to use email as the username. I consider this a bug, but have yet to report it to AWS.

Upvotes: 0

Richard
Richard

Reputation: 1780

Per the documentation there are several property helpers for common attributes like username:

AWSMobileClient.getInstance().getUsername()
AWSMobileClient.getInstance().isSignedIn()
AWSMobileClient.getInstance().getIdentityId()

You can also get the JWT token and then pull out any user attributes:

AWSMobileClient.getInstance().getTokens().getIdToken().getTokenString()

Upvotes: 3

Related Questions