Web与 OC交互总结
1,原生方法,通过url传值
web代码:
<script language="javascript">
function loadURL(url) {
var iFrame;
iFrame = document.createElement("iframe");
iFrame.setAttribute("src", url);
iFrame.setAttribute("style", "display:none;");
iFrame.setAttribute("height", "0px");
iFrame.setAttribute("width", "0px");
iFrame.setAttribute("frameborder", "0");
document.body.appendChild(iFrame);
// 发起请求后这个iFrame就没用了,所以把它从dom上移除掉
iFrame.parentNode.removeChild(iFrame);
iFrame = null;
}
function shareClick() {
//web传参数给iOS,web参数传递通过Url包裹,
loadURL("haleyAction://shareClick?title=测试分享的标题&content=测试分享的内容&url=http://www.baidu.com");
}
</script>
<body>
<input type="button" value="分享" onclick="shareClick()" />
</body>
iOS代码:
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
NSString *requestString = [[request URL] absoluteString];
NSLog(@"拦截请求:%@",requestString);
//requestString
//前端把数据放到requestString中,通过;区分
//有时候根据需要,对url string进行encode和decode
NSArray *components = [requestString componentsSeparatedByString:@";"];
//web:getperfectclick 这种协议定义,ios和android统一
if([components count]>1 && ([[components objectAtIndex:0] isEqualToString:@"web:getperfectclick"]))
{
NSString *element = [components objectAtIndex:1];
//element转成字典
NSDictionary *elementsDic = [element JSONValue];
NSLog(@"%@",elementsDic);
//下面根据字典信息做相应动作
//获取参数后调用OC客户端逻辑
//将OC端获取数据返回给web即手动调用web代码,需要web定义方法,iOS调用
}
return YES;
} - (void)setHtmlData:(NSDictionary *)aDic{
//active.setContentback 这种协议定义,ios和android统一
NSString *resultInfo = [NSString stringWithFormat: @"active.setContentback('%@')",[aDic JSONRepresentation]];
[_webBrowser stringByEvaluatingJavaScriptFromString:resultInfo];
}
优缺点解析
1,原理,规定协议,即url的url的字符串iOS和andriod统一,传参数一样,
2,目前了解到iOS和andriod实现互调在web端的代码不一致
3,web传参给OC通过url,OC传参数web通过调用web定义方法
4,在一套网页请求客户端携带参数,并在客户端获取数据后返回给web端,需要客户端通过url判断web端请求类型和请求参数, 并且web端定义方法,客户端在获取到数据后返回给网页
2,JavaScriptCore
web代码:
<script language="javascript">
function shareClick() {
//调用OC定义的方法
share('测试分享的标题','测试分享的内容','url=http://www.baidu.com');
}
//这个位置接收OC传回的参数
function shareResult(channel_id,share_channel,share_url) {
var content = channel_id+","+share_channel+","+share_url;
asyncAlert(content);
document.getElementById("returnValue").value = content;
}
</script>
<body>
<h1>这是按钮调用</h1>
<input type="button" value="分享" onclick="shareClick()" />
</body>
iOS代码:
-
(void)webViewDidFinishLoad:(UIWebView *)webView
{
JSContext *context = [self.webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
context[@"share"] = ^() {
NSArray *args = [JSContext currentArguments];
if (args.count < 3) {
return ;
}
NSString *title = [args[0] toString];
NSString *content = [args[1] toString];
NSString *url = [args[2] toString];
// 在这里执行分享的操作// 将分享结果返回给js NSString *jsStr = [NSString stringWithFormat:@"shareResult('%@','%@','%@')",title,content,url];
//这个位置将调用js方法,需web定义方法,将参数返回
[[JSContext currentContext] evaluateScript:jsStr];
};
}
优缺点解析
1,获取documentView.webView.mainFrame.javaScriptContext对象,定义OC方法给js调用, 同时在方法内部调用js定义方法将获得参数进行需求处理后获得数据返回
2,在一套网页请求客户端携带参数,并在客户端获取数据后返回给web端,需要客户端定义方法名称网页调用,并处理网页传的请求参数, 最后web端定义方法,客户端在获取到数据后返回给网页
3,WebViewJavascriptBridge框架
web代码:
<script language="javascript">
//定义初始化方法,固定代码
function setupWebViewJavascriptBridge(callback) {
if (window.WebViewJavascriptBridge) { return callback(WebViewJavascriptBridge); }
if (window.WVJBCallbacks) { return window.WVJBCallbacks.push(callback); }
window.WVJBCallbacks = [callback];
var WVJBIframe = document.createElement('iframe');
WVJBIframe.style.display = 'none';
WVJBIframe.src = 'wvjbscheme://BRIDGE_LOADED';
document.documentElement.appendChild(WVJBIframe);
setTimeout(function() { document.documentElement.removeChild(WVJBIframe) }, 0)
}
//执行初始化
setupWebViewJavascriptBridge(function(bridge) {
//注册js方法给客户端调用
bridge.registerHandler('testJSFunction', function(data, responseCallback) {
responseCallback('js执行过了');
})
})
function shareClick() {
var params = {'title':'测试分享的标题','content':'测试分享的内容','url':'http://www.baidu.com'};
//调用OC方法, params为js参数传递给OC, response 为OC处理后返回的数据 WebViewJavascriptBridge.callHandler('shareClick',params,function(response) {
alert(response);
document.getElementById("returnValue").value = response;
});
}
<body>
<h1>这是按钮调用</h1>
<input id = 'shareBtn' type="button" value="分享" onclick="shareClick()" />
</body>
iOS代码:
_webViewBridge = [WebViewJavascriptBridge bridgeForWebView:self.webView];
[_webViewBridge setWebViewDelegate:self];
//OC注册方法给js调用,data为js传入数据
[_webViewBridge registerHandler:@"shareClick" handler:^(id data, WVJBResponseCallback responseCallback) {
// data 的类型与 JS中传的参数有关
NSDictionary *tempDic = data;
// 在这里执行分享的操作
NSString *title = [tempDic objectForKey:@"title"];
NSString *content = [tempDic objectForKey:@"content"];
NSString *url = [tempDic objectForKey:@"url"];
// 将分享的结果返回到JS中
NSString *result = [NSString stringWithFormat:@"分享成功:%@,%@,%@",title,content,url];
//OC将数据返回给网页端
responseCallback(result);
}];
优缺点解析
1, 能实现同时接收网页端数据,并做自己的逻辑处理后返回数据给网页端,网页端拿到数据后进行自己的逻辑处理
2,除了固定初始化代码外,此框架能同时实现双向传值,并在接受到数据后进行自己的逻辑处理 ,不用web端单独定义方法给OC调用来把OC获取的数据传递给网页
4,JavaScriptCore框架iOS封装后
web代码:
function test1() {
var params = {"name":"你","val":"真棒!"};
/*
参数1: 给OC数据
参数2: OC回调给我们的数据
*/
//调用oc代码
mytest(params,function(data) {
alert(data["name2"]);
alert(data["val2"]);
});
}
</script>
</head>
<body id="b1">
<div onclick="test1()" id="a1">aaa</div>
</body>
iOS代码:
(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
return ![self.webView dispatchURL:request.URL];
}-
(NSDictionary *)mytest:(NSDictionary *)params {
NSLog(@"params:%@,%@",params[@"name"],params[@"val"]);
return @{@"name2":@"你",@"val2":@"很棒"};
} (void)webViewDidFinishLoad:(UIWebView *)webView {
// 让js方法和OC方法进行桥接
[webView registerJSMethod:@"mytest" target:self method:@selector(mytest:)];
}
//框架内部实现部分方法
pragma mark - 注册url进行调用OC和js -
- (BOOL)dispatchURL:(NSURL *)url {
if([url.scheme isEqualToString:kBridgeScheme]) {
NSString *jsMethod = url.host;
NSDictionary *invokeParams = [url.query params][@"params"];
NSInvocation *invocation = [[self registeredMethods] objectForKey:jsMethod];
[invocation setArgument:&invokeParams atIndex:2];
__autoreleasing NSDictionary *result = nil;
[invocation invoke];
[invocation getReturnValue:&result];
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:result options:NSJSONWritingPrettyPrinted error:nil];
if(jsonData) {
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSString *js = [NSString stringWithFormat:@"CallbackCaches"%@"",jsMethod,[jsonString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]]];
[self stringByEvaluatingJavaScriptFromString:js];
}
[self stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"CallbackMap["%@"]=NULL;",jsMethod]];
return YES;
}
return NO;
}
pragma mark - 注册方法 -
-
(void)registerJSMethod:(NSString *)jsMethod target:(id)target method:(SEL)method {
//缓存方法
NSMethodSignature *signature = [[target class] instanceMethodSignatureForSelector:method];
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature];invocation.target = target;
invocation.selector = method;NSMutableDictionary *registeredMethods = self.registeredMethods;
[registeredMethods setObject:invocation forKey:jsMethod];//设置回调函数缓存
if(![self isJSVariable:@"CallbackCaches"]) {
[self stringByEvaluatingJavaScriptFromString:@"var CallbackCaches = new Object();"];
}//运行时植入js代码,使js拥有js回调能力
if(![self isJSFunction:jsMethod]) {
NSString *js = [NSString stringWithFormat:@"%@ = function(params,callback){CallbackCaches["%@"]=callback;window.location.href="%@://%@?params="+encodeURIComponent(JSON.stringify(params));}",jsMethod,jsMethod,kBridgeScheme,jsMethod];
[self stringByEvaluatingJavaScriptFromString:js];
}
}