需求
在iOS的UIWebView界面,点击button,直接打开微信跳转到微信小程序。
实现方式
1.接入微信SDK,pod中增加下面一句话
pod 'WechatOpenSDK'
终端中 install pods
2.info-Url Types中添加url
3.Bridging-Header.h的桥头文件中添加
#import "WXApi.h"
#import "WXApiObject.h"
#import <CommonCrypto/CommonCrypto.h>
#import <WechatOpenSDK/WXApi.h>
4.在AppDelegate里实现代理
4.1
funcapplication(_application:UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey:Any]?) ->Bool{
//注册微信 添加小程序ID
WXApi.registerApp("wx3ae562f6a92540bf")
}
4.2
// 这两个方法有一个(sourceApplication)是必须要执行的:反而上面那个openUrl还不执行?当时实现了这两个方法以后回调就开始走了
// 重写AppDelegate的handleOpenURL和openURL方法:
funcapplication(_app:UIApplication, open url:URL, options: [UIApplication.OpenURLOptionsKey:Any] = [:]) ->Bool{
returnWXApi.handleOpen(url, delegate:selfas!WXApiDelegate)
}
4.3 实现相关代理
extension AppDelegate : WXApiDelegate{
/// 微信回调
funconResp(_resp:BaseResp) {
print("errCode =\(resp.errCode)\ntype=\(resp.type)\nerrStr=\(resp.errStr)\nresp=\(resp)")
// errCode = 0 type=0 errStr= resp=<SendMessageToWXResp: 0x281231bf0>
ifresp.errCode==0&& resp.type==0{
/// 微信登录success回调
ifresp.isKind(of:SendAuthResp.classForCoder()) {
letresponse = respas!SendAuthResp
NotificationCenter.default.post(name:Notification.Name(rawValue:"WXLoginSuccessNotification"), object: response.code)
print("微信登录回调返回。。。\(#function)")
}
/// 发送(分享)消息给微信【微信的会话内】【发送至朋友圈】【发送到“我的收藏”】success回调
ifresp.isKind(of:SendMessageToWXResp.classForCoder()) {
print("发送消息给微信列表回调....")
}
}
// 小程序
ifresp.isKind(of:WXLaunchMiniProgramResp.classForCoder()) {
print("小程序回调返回。。。\(resp.errStr), \(resp.errCode)")
}
// 小程序2
// response to H5: extMsg
ifresp.isKind(of:WXLaunchMiniProgramResp.classForCoder()) {
letstr = (respas!WXLaunchMiniProgramResp).extMsg??""
// DDLogDebug("WXLaunchMiniProgramResp-str = \(str)")
// javaScriptToEvalute?.value = ["extMsg": str]
}
}
}
5. 按钮下添加点击事件跳转
letlaunchMiniProgramReq =WXLaunchMiniProgramReq.object()
launchMiniProgramReq.userName= "gh_*****"
launchMiniProgramReq.miniProgramType= .release
WXApi.send(launchMiniProgramReq)
//文中AppID为开发版,所以不能跳转成功,请设置相线上的AppId