unity iOS 微信分享

1. 先到微信开放平台下载SDK

2. 将上图的文件放置在 unity 项目的 Plugin(Plugins)–>iOS 位置下

在这里插入图片描述

3. Unity 中脚本编写

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Runtime.InteropServices;//这是DllImport的头文件
using System.IO;

/// <summary>
/// 下载图片后分享至微信
/// </summary>
public class save : MonoBehaviour {

    //这是调用在 Xcode 写的微信分享的函数
    [DllImport("__Internal")]
    private static extern void ShareByIos(int type,string url);

    private int type = 0;//0:表示分享到聊天;1:表示分享到朋友圈
    
    public void Click0()
    {
        StartCoroutine(SavePic());
        type = 0;
    }

    public void Click1()
    {
        StartCoroutine(SavePic());
        type = 1;
    }
    
    IEnumerator SavePic()
    {
        WWW www = new WWW(url);
        yield return www;
        Debug.Log(www.text);
        Debug.Log(www.error);
        byte[] file = www.bytes;
        int length = file.Length;
        Stream sw;
        FileInfo File = new FileInfo(Application.persistentDataPath+"/证书.png");
        sw = File.Create();
        sw.Write(file, 0, length);
        sw.Close();
        sw.Dispose();
        ShareByIos(type,Application.persistentDataPath + "/证书.png");
    }
}

4. Unity打包 到Xcode

5. Xcode 中的环境配置

  • 导入支持库,下图有8个文件需要导入,libWeChatSDK.a 就是第一步下载的文件,导入进来可以,剩下的7个文件只需要搜索就可以找到导入
    在这里插入图片描述

在这里插入图片描述

  • 在 BuildSetting 中搜索 <OTHER_LDFLAGS>将它的值修改为<-Objc -all_load>,直接将值修改上去即可
    在这里插入图片描述

  • 添加 URL Type
    在这里插入图片描述

  • 添加白名单
    在这里插入图片描述
    找到 info.plist文件,然后添加"LSApplicationQueriesSchemes",这也是没得选,自己添加上去的,然后修改为 Array 类型,然后将LSApplicationQueriesSchemes前面的下拉三角形点击成下拉模式,然后在点击+号,进行添加 item0,item。

  • 将 bitCode 设置为 NO
    在这里插入图片描述

6. Xcode 中 OC 的编写

  • 找到UnityAppController.h文件,然后添加两处地方,如下图一样
#import "WXApi.h"

@interface UnityAppController : NSObject<UIApplicationDelegate,WXApiDelegate>

在这里插入图片描述

  • 找到UnityAppController.mm文件,然后添加下方的代码,添加这段代码的位置必须是在所有的对象都声明完毕的下方添加,不可在该文件的开头文件就把代码贴上去,这样子会造成部分函数没有声明的错误。
#pragma mark - WXApiDelegate

#define WeiXinID @"xxxxxxxxxxxxxx" //这是 AppID


extern "C"
{
    bool isWXAppInstalled()
    {
        return [WXApi isWXAppInstalled];
    }
    bool isWXAppSupportApi()
    {
        return [WXApi isWXAppSupportApi];
    }
    
    //这就是在 Unity 中调用的函数
    void ShareWeChat(const int type, const char*url)
    {
        NSString *picFilePath=[NSString stringWithUTF8String:url];
        WXMediaMessage *message = [WXMediaMessage message];
        [message setThumbImage:[UIImage imageNamed:@"证书.png"]];
        WXImageObject *imageObject = [WXImageObject object];
        imageObject.imageData=[NSData dataWithContentsOfFile:picFilePath];
        message.mediaObject=imageObject;
        SendMessageToWXReq* req = [[SendMessageToWXReq alloc] init];
        req.bText = NO;
        req.message = message;
        req.scene = type == 0 ? WXSceneSession : WXSceneTimeline; // 0:表示聊天,1:表示朋友圈
        [WXApi sendReq:req];
    }
}

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
    return [WXApi handleOpenURL:url delegate:self];
}

- (void)onReq:(BaseReq *)req // 微信向第三方程序发起请求,要求第三方程序响应
{
    
}

- (void)onResp:(BaseResp *)resp // 第三方程序向微信发送了sendReq的请求,那么onResp会被回调
{
    if([resp isKindOfClass:[SendMessageToWXResp class]])
    {
        // 分享
        if(resp.errCode==0)
        {
            NSString *code = [NSString stringWithFormat:@"%d",resp.errCode]; // 0是成功 -2是取消
            NSLog(@"SendMessageToWXResp:%@",code);
            
            //这是给 Unity 发送消息的函数,GameObjectName:Unity 中接收信息的游戏对象的名字;ShareMethod:接收信息的函数,可以在该对象下的任一脚本中的函数
            UnitySendMessage("GameObjectName", "ShareMethod", [code cStringUsingEncoding:NSUTF8StringEncoding]);
        }
    }
}


#pragma mark -

  • 同样还是在UnityAppController.mm文件中,找到openURL函数,将return YES;修改为return [WXApi handleOpenURL:url delegate:self];
- (BOOL)application:(UIApplication*)application openURL:(NSURL*)url sourceApplication:(NSString*)sourceApplication annotation:(id)annotation
{
    NSMutableArray* keys    = [NSMutableArray arrayWithCapacity: 3];
    NSMutableArray* values  = [NSMutableArray arrayWithCapacity: 3];

    #define ADD_ITEM(item)  do{ if(item) {[keys addObject:@#item]; [values addObject:item];} }while(0)

    ADD_ITEM(url);
    ADD_ITEM(sourceApplication);
    ADD_ITEM(annotation);

    #undef ADD_ITEM

    NSDictionary* notifData = [NSDictionary dictionaryWithObjects: values forKeys: keys];
    AppController_SendNotificationWithArg(kUnityOnOpenURL, notifData);
    //return YES;
    return [WXApi handleOpenURL:url delegate:self];
}

  • 同样还是在UnityAppController.mm文件中,找到didFinishLaunchingWithOptions函数,这个函数一般在openURL函数的下方一点点,添加一行代码:
- (BOOL)application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions
{
    [WXApi registerApp:@"appID"];
    ::printf("-> applicationDidFinishLaunching()\n");

7. 打包到手机就可以了


版权声明:本文为star__119原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。