HBuilder webApp development (7) WeChat/QQ/Sina/Tencent Weibo sharing

HBuilder supports WeChat sharing (friends and Moments), QQ sharing, Sina Weibo and Tencent Weibo sharing.
But in the process of using it, the official documents seem to be very tricky.
"Sharing Plug-in Configuration"
and "Sharing Plug-in Development Guide"
are all documents published in July 2014, and I did not see the update instructions later; if users come to ask questions, they will guide them to read these two documents. I really don't know what to look at. of.
In the company's projects, sharing is actually used. When I got home from get off work yesterday, I re-wrote the code and got it past 12 o'clock in the middle of the night.

Configuration of HBuilder

  1. Configure permissions
    Double add manifest.json file, we need to configure permissions first (the default is to have sharing permissions), so we just need to take a look and verify.
    write picture description here

  2. Configure the relevant appkey
    to open the SDK configuration view of manifest.json.
    write picture description here
    We can obtain these appkeys on other third-party platforms for testing. For example ShareSDK. The actual project needs the actual own company. Then select the corresponding platform.

  3. View the code view In the
    write picture description here
    code view, we only need to see these things. no need for correction.

Basic interface and workflow

  1. Interface In the
    write picture description here
    interface , I have listed the existing problems and solutions.
  2. Workflow
    Click the share button in the upper right corner to pop up the share view, select the corresponding platform, and then jump to the corresponding platform. After the sharing is successful, it will return to our application, and the same process is used for native applications. But there is an update sharing service in HBuilder, maybe there is no native registration. See the code below for details.

code

There are some comments in the code, and the usage process will be clearer.

<html>
    <head>
        <meta charset="utf-8">
        <title>Hello MUI</title>
        <meta name="viewport" content="width=device-width, initial-scale=1,maximum-scale=1,user-scalable=no">
        <meta name="apple-mobile-web-app-capable" content="yes">
        <meta name="apple-mobile-web-app-status-bar-style" content="black">
        <!--标准mui.css-->
        <link rel="stylesheet" href="../css/mui.min.css">
        <link rel="stylesheet" href="../css/mui.css" />
        <!--App自定义的css-->
        <style type="text/css">
            .share {
                float: right;
            }
            .tip-title {
                font-size: 20px;
                color: blue;
                padding-left: 10px;
            }
            .content {
                padding-top: 5px;
                padding-bottom: 10px;
                padding-left: 10px;
            }
            .content span {
                color: red;
            }
        </style>
    </head>
    <body>
        <header class="mui-bar mui-bar-nav">
            <a class="mui-action-back mui-icon mui-icon-left-nav mui-pull-left"></a>
            <a class="share mui-icon mui-icon-redo" onclick="shareHref()"></a>
            <h1 class="mui-title">第三方分享</h1>
        </header>
        <div class="mui-content">
            <span class="tip-title">分享平台:</span><br>
            <div class="content">
                1.微信分享:微信好友/微信朋友圈 <br>
                2.QQ分享 <br>
                3.新浪微博分享 <br>
            </div>
            <span class="tip-title">注意事项:</span><br>
            <div class="content">
                <span>
                    微信分享图片大小不能超过32kb限制 <br>
                </span>
            </div>
            <span class="tip-title">解决办法:</span><br>
            <div class="content">
                1.把分享的图片的url转换成图片对象image; <br>
                2.把生成的图片对象image压缩后上传服务器返回新的图片的url; <br>
                3.分享图片地址使用压缩上传后从服务器获取的url; <br>
                或者:<br>
                第一次服务器返回的图片的体积就是32kb以下的. <br>
            </div>
        </div>
    </body>
    <script src="../js/mui.min.js"></script>
    <script src="../js/mui.zoom.js">    </script>
    <script src="../js/mui.previewimage.js"></script>
    <script src="../js/tools.js" ></script>
    <script>

        mui.init({
            swipeBack:true //启用右滑关闭功能
        });

        var Intent = null,
            File = null,
            Uri = null,
            main = null;
        var shares = null;
        var shareImageUrl = '';
        mui.plusReady(function() {  
            updateSerivces();
            if (plus.os.name == "Android") {
                Intent = plus.android.importClass("android.content.Intent");
                File = plus.android.importClass("java.io.File");
                Uri = plus.android.importClass("android.net.Uri");
                main = plus.android.runtimeMainActivity();
            }
        })
        /**
         * 更新分享服务
         */
        function updateSerivces() {
            plus.share.getServices(function(s) {
                shares = {};
                for (var i in s) {
                    var t = s[i];
                    shares[t.id] = t;
                }
                outSet("获取分享服务列表成功");
            }, function(e) {
                outSet("获取分享服务列表失败:" + e.message);
            });
        }
        /**
         * 分享操作
         */
        function shareAction(id, ex) {
            var s = null;
            if (!id || !(s = shares[id])) {
                outLine("无效的分享服务!");
                return;
            }
            if (s.authenticated) {
                outSet("---已授权---");
                shareMessage(s, ex);
            } else {
                outSet("---未授权---");
                s.authorize(function() {
                    shareMessage(s, ex);
                }, function(e) {
                    outLine("认证授权失败");
                });
            }
        }
        /**
         * 发送分享消息
         */
        function shareMessage(s, ex) {
            var msg = {
                content: '分享-详情',
                href: 'http://blog.csdn.net/zhuming3834',
                title: 'HGDQ-分享测试-title',
                content: 'HGDQ-分享测试-content',
                thumbs: ['http://img3.3lian.com/2013/v10/4/87.jpg'],
                pictures: ['http://img3.3lian.com/2013/v10/4/87.jpg'],
                extra: {
                    scene: ex
                }
            };
            s.send(msg, function() {
                outLine("分享成功!");
            }, function(e) {
                outLine("分享失败!");
            });
        }
        /**
         * 分享按钮点击事件
         */
        function shareHref() {
            var ids = [{
                    id: "weixin", 
                    ex: "WXSceneSession"  /*微信好友*/
                }, {
                    id: "weixin",
                    ex: "WXSceneTimeline" /*微信朋友圈*/
                }, {
                    id: "qq"   /*QQ好友*/
                }, {
                    id: "tencentweibo"   /*腾讯微博*/
                },{
                    id: "sinaweibo"  /*新浪微博*/
                }],
                bts = [{
                    title: "发送给微信好友"
                }, {
                    title: "分享到微信朋友圈"
                }, {
                    title: "分享到QQ"
                }, {
                    title: "分享到腾讯微博"
                }, {
                    title: "分享到新浪微博"
                }];
            plus.nativeUI.actionSheet({
                    cancel: "取消",
                    buttons: bts
                },
                function(e) {
                    var i = e.index;
                    if (i > 0) {
                        shareAction(ids[i - 1].id, ids[i - 1].ex);
                    }
                }
            );
        }       
        // 控制台输出日志
        function outSet(msg) {
            console.log(msg);
        }
        // 界面弹出吐司提示
        function outLine(msg) {
            mui.toast(msg);
        }
    </script>
</html>

In actual use, you only need to do this.

pit encountered

When I was working on the native iOS the night before, a bug was raised in the test. In some places, we could call up WeChat to share, but in some places, we couldn't. This problem has occurred before, but other colleagues solved it later. The day before yesterday, I looked at the code of my previous colleague and found the pit inside.
Previously their image compression was using:

UIImageJPEGRepresentation(图片对象,压缩系数) 
// 项目里面压缩系数固定是0.01

Using this method to do, previously solved the problem. Then in the analysis the day before yesterday, it was found that this method sometimes compresses the picture and the larger the volume. For example, the image volume is only 37kb, and it may be about 58kb after compression, but for a 500+kb image, the compressed image volume can reach below 32kb. (WeChat of all evil, 32kb limit of all evil) .
Finally, it is analyzed that the shared picture is used there. The small picture on the
write picture description here
left is shared.
Think about the method you used when you made a QR code by yourself before ( 《CoreImage Native QR Code Generation (1)》 ).
My solution is to directly compress the image compressed by calling UIImageJPEGRepresentation above into an image of the specified size, and then share it.

/**
 *  大图片压缩成制定尺寸的图片
 *
 *  @param img  需要压缩的图片
 *  @param size 目标尺寸
 *
 *  @return 压缩后的图片
 */
+ (UIImage *)scaleTosize:(UIImage *)img size:(CGSize)size{
    // 创建一个bitmap的context
    // 并把它设置成为当前正在使用的context
    UIGraphicsBeginImageContext(size);
    [img drawInRect:CGRectMake(0, 0, size.width, size.height)];
    UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    return scaledImage;
}

You can check the previous blog for the method I used in the above QR code generation.

However, the url of the image shared in HBuilder, even if the image obtained through the url finally exceeds 32kb, cannot be shared using WeChat.
The solution is:
1. Convert the url of the shared image into an image object image;
2. Compress the generated image object image and upload the server to return the url of the new image;
3. The shared image URL is obtained from the server after uploading through compression url;
or:
the size of the image returned by the server for the first time is less than 32kb.
The limit of 32kb for sharing pictures on Wechat made me a fool last night, and finally found the answer on HBuilder's official website, but in the end it was fruitless. After thinking about it, I just solved this problem the day before yesterday. The problem is that WeChat has a limit on the size of pictures shared from Apple's mobile phone. Actually, there is no limit on Android machines.

finally

Regarding the renderings, you can go to my github to download and view, the uploaded pictures on CSDN cannot exceed 2M.
Code download address: please click me!

Update log:
2016.07.12
At the request of CSDN netizen u012155655 , Tencent Weibo sharing has been added, and the github code has been updated.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325404302&siteId=291194637