目录

更新关键资产(ArkTS)

接口介绍

开发者可以查阅API文档,获取关键资产更新接口的详细说明:异步接口update(query: AssetMap, attributesToUpdate: AssetMap)、同步接口updateSync(query: AssetMap, attributesToUpdate: AssetMap)。

在更新关键资产时,关键资产属性的内容(AssetMap)参数如下表所示:

下表中“ALIAS”和名称包含“DATA_LABEL”的关键资产属性,用于存储业务自定义信息,其内容不会被加密,请勿存放敏感个人数据。

代码示例

本模块提供了异步和同步两套接口,以下为异步接口的使用示例,同步接口详见@ohos.security.asset (关键资产存储服务)。

在指定群组中更新一条关键资产的使用示例详见更新群组关键资产。

在更新前,需确保已有关键资产,可参考指南文档新增关键资产,否则将抛出NOT_FOUND错误(错误码24000002)。

更新别名是demo_alias的关键资产,将关键资产明文更新为demo_pwd_new,附属属性更新成demo_label_new。

  1. 引用头文件,定义工具函数。

    import { asset } from '@kit.AssetStoreKit';
    import { util } from '@kit.ArkTS';
    import { BusinessError } from '@kit.BasicServicesKit';
    
    function stringToArray(str: string): Uint8Array {
      let textEncoder = new util.TextEncoder();
      return textEncoder.encodeInto(str);
    }
  2. 参考如下示例代码,进行业务功能开发。

    let query: asset.AssetMap = new Map();
    query.set(asset.Tag.ALIAS, stringToArray('demo_alias'));
    let attrsToUpdate: asset.AssetMap = new Map();
    attrsToUpdate.set(asset.Tag.SECRET, stringToArray('demo_pwd_new'));
    attrsToUpdate.set(asset.Tag.DATA_LABEL_NORMAL_1, stringToArray('demo_label_new'));
    try {
      asset.update(query, attrsToUpdate).then(() => {
        console.info(`Succeeded in updating Asset.`);
        // ...
      }).catch((err: BusinessError) => {
        console.error(`Failed to update Asset. Code is ${err.code}, message is ${err.message}`);
        // ...
      });
    } catch (error) {
      let err = error as BusinessError;
      console.error(`Failed to update Asset. Code is ${err.code}, message is ${err.message}`);
      // ...
    }