关于交互实现方式的选择。
网上讨论比较多的有一个第三方库WebViewJavascriptBridge,个人不建议用,因为本身我们在做H5交互的时候就是给前端增加了工作量,而这种处理方式就需要前端要配置两套代码,一套给安卓,一套给iOS,而且不利于调试。所以我最后选择用系统的JavaScriptCore框架,JavaScriptzCore内部有五个框架,分别是:
#import "JSContext.h",
#import "JSValue.h",
#import "JSManagedValue.h",
#import "JSVirtualMachine.h",
#import "JSExport.h"
本文只讲常用的JSContext和JSValue,JSExport这三个类。
下面直接上代码
#import "ViewController.h"
#import <JavaScriptCore/JavaScriptCore.h>
@protocol JSObjcDelegate <JSExport>
// 调用相册
- (void)callCamera;
// 分享字符串
- (void)shareToObjc:(NSString *)shareString;
@end
@interface ViewController ()<UIWebViewDelegate,JSObjcDelegate>
@property (nonatomic,strong) JSContext *jsContext;
@property (weak, nonatomic) IBOutlet UIWebView *webView;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
NSURL* url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"test" ofType:@"html"]];
[self.webView loadRequest:[NSURLRequest requestWithURL:url]];
}
#pragma mark UIWebViewDelegate
- (void)webViewDidFinishLoad:(UIWebView *)webView {
self.jsContext = [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
__weak typeof(self) selfVc = self;
// //建立HH这个界面与当前控制器的关联
self.jsContext[@"HH"] = selfVc;
self.jsContext.exceptionHandler = ^(JSContext *context, JSValue *exception) {
NSLog(@"异常信息:%@",exception);
};
}
#pragma mark JSObjcDelegate
- (void)shareToObjc:(NSString*)shareString {
NSLog(@"%@",shareString);
[self.jsContext[@"shareCallback"] callWithArguments:@[@"成功!"]];
}
- (void)callCamera {
JSValue* picCallback = self.jsContext[@"picCallback"];
[picCallback callWithArguments:@[@"图片"]];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
//- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
// NSString *url = request.URL.absoluteString;
// if ([url rangeOfString:@"HH://"].location != NSNotFound) {
// NSLog(@"callCamera");
// return NO;
// }
// return YES;
//}
@end
HTML代码:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<script>
var callShare = function()
{
var shareInfo = JSON.stringify({"title": "标题", "desc": "内容", "shareUrl": "http://www.baidu.com","shareIco":"https://ss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/logo/logo_white_fe6da1ec.png"});
HH.shareToObjc(shareInfo);
}
var picCallback = function(photos)
{
alert(photos);
}
var shareCallback = function(string)
{
alert(string);
}
</script>
</head>
<body>
<h1>Objective-C和JavaScript交互的那些事</h1>
<div>
<input type="button" value="调用相册" onclick="HH.callCamera()">
</div>
<div>
<input type="button" value="分享字符串" onclick="callShare()">
</div>
</body>
</html>