iOS 开发之与JS交互

本文介绍了一种使用JavaScriptCore框架实现Objective-C与JavaScript交互的方法,避免了使用WebViewJavascriptBridge带来的不便。通过具体代码示例展示了如何在iOS应用中设置JavaScript上下文并与HTML页面进行双向通信。

关于交互实现方式的选择。

网上讨论比较多的有一个第三方库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>

 

转载于:https://my.oschina.net/zsyzone/blog/755767

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值