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
接下来我们要在.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>JS与OC交互</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>
- iOS 实现OC与JS(JavaScript)混编
- OC与JS的交互(iOS与H5混编)
- ios ——JS 与OC混编
- IOS --- OC与Swift混编
- iOS开发之Swift与OC混编实现
- iOS代码规范(Swift 与 OC 混编版)
- IOS --- OC与Swift混编
- IOS --- OC与Swift混编
- 如何实现OC与Swift混编
- 使用JSCore- iOS 原生的框架实现js和oc混编
- iOS C++/OC 混编
- MVC Razor与javascript混编(js中嵌入razor)
- swift与OC混编(创建混编工程)
- 如果实现Swift --- OC混编(swift)
- iOS开发——OC和JS混编
- swift与OC混编(方法调用)
- Swift与OC混编
- vc 与oc混编
- csv文件导入到mysql
- 如何对已经打包好的ipa包进行签名
- 对线程创建函数pthread_create的总结
- [Linux][入门系列]CentOS 的基础使用-yum使用手册(上)
- java泛型详解
- iOS 实现OC与JS(JavaScript)混编
- 状压DP
- Grunt、Gulp区别 webpack、 requirejs区别
- Anbox:容器中的 Android
- Centos6.5下 logstash5.2.2的安装 + log4j模式 (实践成功)
- arguments实参集合&参数&局部变量的关系
- Linux查看硬盘总空间和未分配硬盘大小
- java的对象祖先Object的源码
- 算法和算法分析概念