iOS 实现OC与JS(JavaScript)混编

来源:互联网 发布:linux 绑核 编辑:程序博客网 时间:2024/06/05 21:54

首先,我们要想实现OC掉用JS我们倒入一个官方提供的包

#import <JavaScriptCore/JavaScriptCore.h>

导入以后,我们要创建一个对象

@property (nonatomic,strong) JSContext *jsContext;

接下来我们要做的就是定义一个协议

@protocol JSObjcDelegate <JSExport>

- (void)getCall:(NSString *)callString;

@end

我们要创建一个WebView因为我们要实现,页面的加载,JS使用
以上效果图:


接下来我们要在.m文件 写代码

代码如下:


- (void)viewDidLoad {

    [superviewDidLoad];

   

}


-(void)viewDidAppear:(BOOL)animated{

    _webView = [[UIWebViewalloc]initWithFrame:CGRectMake(0,20, [UIScreenmainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height)];

    _webView.delegate =self;

    

    NSString* path = [[NSBundlemainBundle] pathForResource:@"index"ofType:@"html"];

    NSURL* url = [NSURLfileURLWithPath:path];

    NSURLRequest* request = [NSURLRequestrequestWithURL:url] ;

    [_webViewloadRequest:request];

    

    [self.viewaddSubview:_webView];

}


- (void)webViewDidFinishLoad:(UIWebView *)webView {

    _jsContext = [webViewvalueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];

    _jsContext[@"xyc"] =self;// 这里的xyc是要与JS中的要对应

    _jsContext.exceptionHandler = ^(JSContext *context,JSValue *exceptionValue) {

        context.exception = exceptionValue;

       // NSLog(@"异常信息:%@", exceptionValue);

    };

}


//- (void)call{

//    NSLog(@"call");

//    // 之后在回调js的方法Callback把内容传出去

//    JSValue *Callback = _jsContext[@"Callback"];

//    //传值给web

//    [Callback callWithArguments:@[@"唤起本地OC回调完成"]];

//}


- (void)getCall:(NSString *)callString{

    NSLog(@"Get:%@", callString);//这里是获取JS传过来的内容通过xyc.getCall传过来的值

    // 成功回调js的方法Callback

    

    

//    直接添加提示框

//    NSString *str = @"alert('OC添加JS提示成功')";

//    [_jsContext evaluateScript:str];


}

这样OC代码基本就完事了

JS代码

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

</head>

<body>

<div style="margin-top: 20px">

<h2>JSOC交互</h2>


</div>

<div>

<input type="button"value "唤起getCall:(NSString *)callString传值"  onclick="requestCoBrandedCard()">

</div>


<script>

    

    function requestCoBrandedCard(){

        

        var u=navigator.userAgent;

        if(u.indexOf('iPhone')>-1){

            //var callInfo = JSON.stringify("http://www.baidu.com");

            xyc.getCall("http://www.baidu.com");//这里和OC中的xyc对应通过协议便可以实现OC中获取xyc.getCall穿过去的内容

        }else{

            window.android.actionFromJsWithParam('http://www.baidu.com')

        }

        

    }

    

</script>

</body>

</html>

这样节本就实现了代码
项目目录:
项目代码下载路径:http://download.csdn.net/detail/wangqinglei0307/9821352

0 0
原创粉丝点击