实例书写不是很好看,但是例子都是验证过的,也给自己后面的时候直接拿走调用
用例.例如,js中调用原生微信分享方法.
1.首先在oc代码中提供微信分享的方法
import <JavaScriptCore/JavaScriptCore.h>
import <WebKit/WebKit.h>
import "WXApi.h"
-
(void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
configuration.preferences = [[WKPreferences alloc] init];configuration.preferences.minimumFontSize = 10;
configuration.preferences.javaScriptEnabled = YES;
configuration.preferences.javaScriptCanOpenWindowsAutomatically = YES;
configuration.userContentController = [[WKUserContentController alloc] init];configuration.processPool = [[WKProcessPool alloc] init];
self.webView= [[WKWebView alloc]initWithFrame:self.view.bounds configuration:configuration];
self.webView.backgroundColor = [UIColor grayColor];
self.webView.UIDelegate = self;
self.webView.navigationDelegate =self;
[self.view addSubview:self.webView];
NSString* path = [[NSBundle mainBundle] pathForResource:@"test11" ofType:@"html"];
NSURL* url = [NSURL fileURLWithPath:path];
NSURLRequest *request =[NSURLRequest requestWithURL:url];
[self.webView loadRequest:request];
//注册方法 (微信分享的方法,还可以注册其他很多方法)
[configuration.userContentController addScriptMessageHandler:self name:@"sharewithwx"];
}
代理方法
- (void)userContentController:(WKUserContentController)userContentController didReceiveScriptMessage:(WKScriptMessage)message
{
NSLog(@"message.name====%@ body=%@",message.name,message.body);
NSDictionary *obj = message.body;
NSString *title = obj[@"title"];
NSString *description=obj[@"description"];
NSString *webpageUrl=obj[@"webpageUrl"];
NSString *thumbImage=obj[@"thumbImage"];
if([message.name isEqualToString:@"sharewithwx"])
{
[self sharewithwx:title :description :webpageUrl :thumbImage];
}
}
-
(void)sharewithwx:(NSString *)title :(NSString *)description :(NSString *)webpageUrl :(NSString *)thumbImage
{
if([WXApi isWXAppInstalled]){//判断当前设备是否安装微信客户端//创建多媒体消息结构体 WXMediaMessage *message = [WXMediaMessage message]; message.title = title; message.description = description;//描述 [message setThumbImage:[UIImage imageNamed:thumbImage]];//设置预览图 //创建网页数据对象 WXWebpageObject *webObj = [WXWebpageObject object]; webObj.webpageUrl = webpageUrl;//链接 message.mediaObject = webObj; SendMessageToWXReq *sendReq = [[SendMessageToWXReq alloc] init]; sendReq.bText = NO;//不使用文本信息 sendReq.message = message; sendReq.scene = WXSceneSession;//分享到好友会话 [WXApi sendReq:sendReq];//发送对象实例
}else{
//未安装微信应用或版本过低
}
}
js中的调用.test11.html如下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script>
function onshow() {
window.webkit.messageHandlers.sharewithwx.postMessage({title:'【爆款直降 盛夏特惠】【29.9免邮 限量买3免1】清新持久自然GUCCMI香水',description:'我在京东发现了一个不错的商品,赶快来看看吧。',webpageUrl:'[https://open.weixin.qq.com](https://open.weixin.qq.com)',thumbImage:'res2.png'})
}
</script>
</head>
<body>
<br>
<br>
<br>
<button id="it" type="button" style="font-size: 100px" onclick="onshow()">点我有惊喜</button>
</body>
</html>
网友评论