简体   繁体   中英

How do a get a specific attribute from AWS Cognito user pools after user?.getDetails call

After signing in successfully I want to get the value of a particular attribute. Is it possible to do this without iterating through each attribute? I know I can't subscript but is there any other way?

So in the example below what I want is the value of the user's email. Ideally, I would like to say let email = userAttributes["email"] but this type does not allow subscription.

user?.getDetails().continueOnSuccessWith(block: { (task) -> Any? in
    let userAttributes = task.result?.userAttributes

    for attribute in userAttributes! {
        print(attribute.name!)
        print(attribute.value!)
    }
    return nil
})

Seeing that AWSCognitoIdentityProviderAttributeType contains both a name and a value, we can easily map over that data to make a dictionary that can be accessed by a key value.

Add this extension somewhere

extension Array where Element: AWSCognitoIdentityProviderAttributeType {
    func dict() -> [String : String] {
        var dict: [String : String] = [:]
        self.forEach({ e in dict[e.name!] = e.value! })
        return dict
    }
}

then use

task.result?.userAttributes.dict()[...]

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