HarmonyOS 通过Promise来使用Sharekit时,systemShare会为undefined?

通过Promise来使用Sharekit时,systemShare会为undefined,会走Error逻辑并报错:

TypeError: Cannot read property SharedData of undefined@36b6d299。

代码如下:

openShare(): Promise < void> {
    return new Promise((resolve, reject) => {
        try {
            let data: systemShare.SharedData = new systemShare.SharedData({
                utd: utd.UniformDataType.PLAIN_TEXT,
                content: 'Hello HarmonyOS'
            });
            data.addRecord({
                utd: utd.UniformDataType.PNG,
                uri: ''
            });
            let controller: systemShare.ShareController = new systemShare.ShareController(data);
            // 获取UIAbility上下文对象
            let context: common.UIAbilityContext = getContext(this) as common.UIAbilityContext;
            controller.show(context, {
                previewMode: systemShare.SharePreviewMode.DETAIL,
                selectionMode: systemShare.SelectionMode.SINGLE
            });
            resolve()
        } catch (e) {
            console.error(e.message)
            this.errmsg = e.message
            reject(e)
        }
    })
}
阅读 486
1 个回答

参考下面代码,目前只支持华为分享:

import { systemShare } from '@kit.ShareKit';
import { common } from '@kit.AbilityKit';
import { uri } from '@kit.ArkTS';
import { promptAction } from '@kit.ArkUI';
import { uniformTypeDescriptor } from '@kit.ArkData';


@Entry
@Component
struct SharePage {
  private context = getContext(this) as common.UIAbilityContext
  @State message: string = 'Hello World';

  build() {
    Row() {
      Column() {
        Button('分享 - 网站').margin({ bottom: 10 })
          .onClick(() => {
            this.shareWebSite(this.context, 'www.harmonyos.com', 'HarmonyOS')
          })
      }
      .width('100%')
    }
    .height('100%')
  }

  // 分享网站
  shareWebSite(context: common.UIAbilityContext, url: string, title: string, thumbnail?: Uint8Array): void {
    try {
      // 构造ShareData,需配置一条有效数据信息
      let data: systemShare.SharedData = new systemShare.SharedData({
        utd: uniformTypeDescriptor.UniformDataType.HYPERLINK,
        content: url,
        title: title,
        description: url,
      });
      let controller: systemShare.ShareController = new systemShare.ShareController(data);
      controller.on('dismiss', () => {
        promptAction.showToast({
          message: 'Share panel disappeared'
        });
      });
      controller.show(context, {
        previewMode: systemShare.SharePreviewMode.DETAIL,
        selectionMode: systemShare.SelectionMode.SINGLE
      });
    } catch (e) {
      const error = e as Error;
      console.error('share error: ' + error.message);
    }
  }
}

参数参考文档:https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/share-system-share-V5\#section20696483813

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进