美文网首页React Native学习
react-native 分享微信小程序(react-nativ

react-native 分享微信小程序(react-nativ

作者: 既然可以颠覆何必循规蹈矩 | 来源:发表于2018-10-22 09:55 被阅读87次

勤做笔记,方便自己,帮助他人。

1.替换本地的微信sdk。

SDK下载地址

ios 修改部分代码

1. RctWeChat/RCTWeChat.h 文件中的第25行 加上

#define RCTWXShareTypeMini @"mini"

截图如下:

1.png



2. RctWeChat/RCTWeChat.m 的第282行 加入一个else

 else if ([type isEqualToString:RCTWXShareTypeMini]) {
            WXMiniProgramObject *miniObject = [WXMiniProgramObject object];
            miniObject.webpageUrl = aData[@"webpageUrl"];
            miniObject.userName = aData[@"userName"];
            miniObject.path = aData[@"path"];
            miniObject.withShareTicket = [aData[@"withShareTicket"] boolValue];
            miniObject.miniProgramType = [aData[@"miniProgramType"] integerValue];
            miniObject.hdImageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:aData[@"hdImageData"]]] ;
            
            [self shareToWeixinWithMediaMessage:aScene
                                          Title:title
                                    Description:description
                                         Object:miniObject
                                     MessageExt:messageExt
                                  MessageAction:messageAction
                                     ThumbImage:aThumbImage
                                       MediaTag:mediaTagName
                                       callBack:callback];
            
        }

截图如下:

2.png



3. RctWeChat/RCTWeChat.m 第74行 修改为

callback(@[[WXApi registerApp:appid ] ? [NSNull null] : INVOKE_FAILED]);

截图如下:


3.png



android

1.修改引用方式 android/app/build.gradle 中添加compile project(':react-native-wechat')引用

4.png
  1. android/src/main/java/com/theweflex/react/WeChatModule.java中 添加
    import com.tencent.mm.opensdk.modelmsg.WXMiniProgramObject;引用

    5.png
  2. android/src/main/java/com/theweflex/react/WeChatModule.java 中修改代码


    ![![8.png](https://img.haomeiwen.com/i4770957/f745970b273fecaa.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ](https://img.haomeiwen.com/i4770957/438a351ec99dd77f.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
if (data.hasKey("thumbImage") || data.hasKey("hdImageData")) {
            String imageUrl = data.hasKey("hdImageData") ? data.getString("hdImageData") : data.getString("thumbImage");

            try {
                uri = Uri.parse(imageUrl);
                // Verify scheme is set, so that relative uri (used by static resources) are not handled.
                if (uri.getScheme() == null) {
                    uri = getResourceDrawableUri(getReactApplicationContext(), imageUrl);
                }
            } catch (Exception e) {
                // ignore malformed uri, then attempt to extract resource ID.
            }
        }

新增方法

 private void __jsonToImageMedia(String imageUrl, final MediaObjectCallback callback) {
        Uri imageUri;
        try {
            imageUri = Uri.parse(imageUrl);
            // Verify scheme is set, so that relative uri (used by static resources) are not handled.
            if (imageUri.getScheme() == null) {
                imageUri = getResourceDrawableUri(getReactApplicationContext(), imageUrl);
            }
        } catch (Exception e) {
            imageUri = null;
        }

        if (imageUri == null) {
            callback.invoke(null);
            return;
        }

        this._getImage(imageUri, null, new ImageCallback() {
            @Override
            public void invoke(@Nullable Bitmap bitmap) {
                callback.invoke(bitmap == null ? null : new WXImageObject(bitmap));
            }
        });
    }



最后js部分

提取公用方法


image.png

和之前的分享像是一样 只是修改几个参数就行(小程序只能分享给好友)

async function shareToWeChat(params) {
    const {
        url,
        img_small,
        label,
        title,
        path,
        description,
    } = params;

    try {
        const isInstalled = await WeChat.isWXAppInstalled();
        if (!isInstalled) {
            Alert.alert('没有安装微信', '请先安装微信客户端', [
                { text : '确定' }
            ]);
            return false
        }

      /**
       * thumbImage - Thumb image of the message, which can be a uri or a resource id.  消息的Thumb图像,可以是uri或资源id
       * type - Type of this message. Could be {news|text|imageUrl|imageFile|imageResource|video|audio|file|mini}
       * webpageUrl - Required if type equals news or mini. The webpage link to share.  如果是网页或者小程序  网页地址
       * userName - 小程序的原生id.
       * path - 小程序页面的路径.
       * description - 描述
       * hdImageData - 小程序节点高清大图,小于128k.
       * withShareTicket - 是否使用带 shareTicket 的转发
       * miniProgramType - 分享小程序的版本(0-正式,1-开发,2-体验)
       *
       * imageUrl - Provide a remote image if type equals image. 如果type为image,则使用此分享url
       * videoUrl - Provide a remote video if type equals video. 如果type为video,则使用此分享url
       * musicUrl - Provide a remote music if type equals audio. 如果type为audio,则使用此分享url
       * filePath - 如果type为file,则使用此获取本地文件
       * fileExtension - String 如果type为file,则使用此提供文件类型
       */
        const obj = {
            type : label === '微信' ? 'mini' : 'news',
            title : title,
            description: description || '收录全国各楼盘渠道在售户型/分销政策,帮助经纪人快速找房',
            webpageUrl : url,
            thumbImage : img_small,

            path,
            hdImageData:img_small,
            miniProgramType : 2,
            userName : 'gh_beca976899fb',
            withShareTicket : false,
        };

        if (label === '微信') {
            const res = await WeChat.shareToSession(obj);
            return res.errCode === 0

        } else if (label === '微信朋友圈') {
            const res = await WeChat.shareToTimeline(obj);
            return res.errCode === 0
        }
    } catch (err) {
        console.log(err);
    }
}

页面调用

async _shareToWeChat(label) {
        const {buildingUrl, building_cover_small, name} = this.state.data;
        const data = {
            url: buildingUrl,
            img_small: building_cover_small,
            label,
            path: '/pages/list/list',
            title: name,
        };

        const res = await shareToWeChat(data);
        if (res) {
            Toast.success('分享成功', 2);
            this.setState({shareVisible: false});
        } else {
            Toast.success('分享失败', 2);
        }
    }

参考文章: https://github.com/yorkie/react-native-wechat/pull/381

相关文章

网友评论

本文标题:react-native 分享微信小程序(react-nativ

本文链接:https://www.haomeiwen.com/subject/ykyfzftx.html