#鸿蒙学习大百科#客户端如何获取用户的头像、昵称等信息?

客户端如何获取用户的头像、昵称等信息?

HarmonyOS
2024-10-23 09:36:04
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
耗子煨汁r
import { authentication } from '@kit.AccountKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { util } from '@kit.ArkTS';

// 创建授权请求,并设置参数
let authRequest = new authentication.HuaweiIDProvider().createAuthorizationWithHuaweiIDRequest();
// 获取头像昵称需要传如下scope
authRequest.scopes = ['profile'];
// 若开发者需要进行服务端开发,则需传如下permission获取authorizationCode
authRequest.permissions = ['serviceauthcode'];
// 用户是否需要登录授权,该值为true且用户未登录或未授权时,会拉起用户登录或授权页面
authRequest.forceAuthorization = true;
authRequest.state = util.generateRandomUUID();
@Entry
@Component
struct Index {
  build() {
    Column() {
      Button("获取用户信息").onClick(() => {
        // 执行授权请求
        try {
          let controller = new authentication.AuthenticationController(getContext(this));
          controller.executeRequest(authRequest, (err, data) => {
            if (err) {
              hilog.error(0x0000, 'testTag', 'auth fail,error: %{public}s', JSON.stringify(err));
              return;
            }
            let authorizationWithHuaweiIDResponse = data as authentication.AuthorizationWithHuaweiIDResponse;
            let state = authorizationWithHuaweiIDResponse.state;
            if (state != undefined && authRequest.state != state) {
              hilog.error(0x0000, 'testTag', 'auth fail,The state is different: %{public}s',
                JSON.stringify(authorizationWithHuaweiIDResponse));
              return;
            }
            hilog.info(0x0000, 'testTag', 'auth success: %{public}s',
              JSON.stringify(authorizationWithHuaweiIDResponse));
            let authorizationWithHuaweiIDCredential = authorizationWithHuaweiIDResponse.data!;
            let avatarUri = authorizationWithHuaweiIDCredential.avatarUri;//用户头像
            let nickName = authorizationWithHuaweiIDCredential.nickName;//用户昵称
            let authorizationCode = authorizationWithHuaweiIDCredential.authorizationCode;
            // 开发者处理avatarUri, nickName, authorizationCode
            hilog.error(0x0000,'testTag',"avatarUri:"+avatarUri?.toString())
            hilog.error(0x0000,'testTag',"nickName:"+nickName?.toString())
          });
        } catch (error) {
          hilog.error(0x0000, 'testTag', 'auth failed: %{public}s', JSON.stringify(error));
        }
      })
    }
    .width('100%')
    .height('100%')
    .justifyContent(FlexAlign.Center)
  }
}

分享
微博
QQ
微信
回复
2024-10-23 16:26:28
相关问题
使用Account Kit 获取用户头像昵称
316浏览 • 1回复 待解决
取消Account Kit 获取用户头像昵称授权
407浏览 • 1回复 待解决
客户端开发无法获取code
256浏览 • 1回复 待解决
#鸿蒙学习大百科#什么是用户文件?
156浏览 • 0回复 待解决