You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift环境下如何从AWS Cognito获取已登录用户的用户名?

获取AWS Cognito已登录用户的用户名

嘿,这不复杂!在你登录成功的回调里,只需要几步就能拿到已登录用户的用户名,我帮你修改下代码并解释清楚:

首先,直接在你现有的completionHandler里添加获取逻辑就行,利用AWS提供的AWSSignInManager来获取当前登录用户:

AWSAuthUIViewController.presentViewController(
    with: self.navigationController!,
    configuration: config,
    completionHandler: { (provider: AWSSignInProvider, error: Error?) in
        if error == nil {
            // 关键:获取当前登录的Cognito用户实例
            if let currentUser = AWSSignInManager.sharedInstance().currentUser() as? AWSCognitoIdentityUser {
                let username = currentUser.username
                print("当前登录的用户名是:\(username)")
                // 这里就可以把username用在你需要的业务逻辑里啦
            }
        } else {
            print(error as Any)
        }
    }
)

简单解释下逻辑:

  • 登录成功后,AWSSignInManager.sharedInstance().currentUser()会返回当前的登录用户对象,我们把它强制转换为AWSCognitoIdentityUser类型(因为Cognito的用户对象实现了AWSSignInProvider协议)。
  • 之后直接访问username属性就能拿到用户在Cognito里注册的用户名了,就是这么简单!

另一种获取方式(适合在其他页面/场景使用)

如果你在登录流程之外的地方需要获取当前用户的用户名,也可以直接通过你的Cognito用户池实例来获取:

// 这里的"YourUserPoolKey"是你在AWS配置文件里设置的用户池key
let userPool = AWSCognitoIdentityUserPool(forKey: "YourUserPoolKey")
if let currentUser = userPool.currentUser() {
    let username = currentUser.username
    print("当前登录用户名:\(username)")
}

内容的提问来源于stack exchange,提问作者froggomad

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:56:55