如何在AWS Cognito调用user?.getDetails后获取指定用户属性?
问题:如何直接获取AWS Cognito用户池特定属性值(无需遍历)
我成功登录后,希望获取AWS Cognito用户池中某个特定属性的值,是否可以不用遍历所有属性实现?我知道无法通过下标访问,请问有其他方法吗?例如我想获取用户的邮箱值,理想方式是使用let email = userAttributes["email"],但该类型不支持下标操作。当前我的代码如下:
user?.getDetails().continueOnSuccessWith(block: { (task) -> Any? in let userAttributes = task.result?.userAttributes for attribute in userAttributes! { print(attribute.name!) print(attribute.value!) } return nil })
回答
当然可以不用遍历所有属性!我之前也碰到过这个需求,其实只需要把Cognito返回的属性数组转换成字典,就能像你期待的那样通过键名直接访问对应值了。
给你修改后的代码示例,还加入了安全的可选绑定避免崩溃:
user?.getDetails().continueOnSuccessWith(block: { (task) -> Any? in // 先安全获取属性数组,避免强制解包 guard let userAttributes = task.result?.userAttributes else { print("无法获取用户属性") return nil } // 将属性数组转换为[String: String]类型的字典 let attributeDict = userAttributes.reduce(into: [String: String]()) { result, attribute in // 只处理有有效名称和值的属性 if let name = attribute.name, let value = attribute.value { result[name] = value } } // 现在就能直接通过key获取邮箱啦 if let email = attributeDict["email"] { print("用户邮箱:\(email)") } // 其他属性也可以这样直接获取,比如昵称、手机号 if let nickname = attributeDict["nickname"] { print("用户昵称:\(nickname)") } return nil })
这个方法的优势很明显:一次性转换后,后续需要访问任何属性都不用再遍历数组,代码更简洁易读,还能避免重复遍历带来的性能损耗。另外一定要注意避免像原代码那样用!强制解包,用guard和可选绑定处理空值会让你的代码更健壮。
内容的提问来源于stack exchange,提问作者alionthego
相关产品推荐
相关产品推荐

