目录

批量更新关键资产(ArkTS)

接口介绍

从版本26.0.0开始,系统提供异步接口batchUpdate以便开发者批量更新关键资产。

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

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

约束和限制

批量更新的关键资产必须具有相同的GROUP_ID和REQUIRE_ATTR_ENCRYPTED属性。

批量更新的关键资产数量最大值为100。

开发步骤

以下为批量更新接口的使用示例。

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

批量更新两条关键资产,将别名分别为demo_alias1和demo_alias2的关键资产明文更新为demo_pwd_new1和demo_pwd_new2。

  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 srcAttrs: asset.AssetMap[] = [];
    let srcAttr1: asset.AssetMap = new Map();
    srcAttr1.set(asset.Tag.ALIAS, stringToArray('demo_alias1'));
    srcAttrs.push(srcAttr1);
    let srcAttr2: asset.AssetMap = new Map();
    srcAttr2.set(asset.Tag.ALIAS, stringToArray('demo_alias2'));
    srcAttrs.push(srcAttr2);
    
    let destAttrs: asset.AssetMap[] = [];
    let destAttr1: asset.AssetMap = new Map();
    destAttr1.set(asset.Tag.SECRET, stringToArray('demo_pwd_new1'));
    destAttrs.push(destAttr1);
    let destAttr2: asset.AssetMap = new Map();
    destAttr2.set(asset.Tag.SECRET, stringToArray('demo_pwd_new2'));
    destAttrs.push(destAttr2);
    
    try {
      asset.batchUpdate(srcAttrs, destAttrs).then((res: asset.BatchResult) => {
        console.info(`Succeeded in batch updating Asset, failedCount: ${res.failedCount}`);
        if (res.failedCount > 0) {
          for (let i = 0; i < res.failedErrorInfos.length; i++) {
            console.error(`Failed to update Asset at index ${res.failedErrorInfos[i].index},
              errCode: ${res.failedErrorInfos[i].errCode}, message: ${res.failedErrorInfos[i].message}`);
          }
        }
      }).catch((err: BusinessError) => {
        console.error(`Failed to batch update Asset. Code is ${err.code}, message is ${err.message}`);
      })
    } catch (error) {
      let err = error as BusinessError;
      console.error(`Failed to batch update Asset. Code is ${err.code}, message is ${err.message}`);
    }