JS和OC的交互

第一種方法,利用 UIWebView 的 delegate方法

- (void)viewDidLoad {
[super viewDidLoad];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"https://www.baidu.com"]];
[self.webView loadRequest:request];
self.webView.delegate = self;    
}
#pragma mark - UIWebViewDelegate
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
NSURL *url = [request URL];
NSString *urlStr = [NSString stringWithFormat:@"%@",url];
NSLog(@"%@",urlStr);
return YES;
}

根據(jù)代理方法,當(dāng)點擊 html 頁面的請求時,可以返回請求的 url ,

第二種方法是利用 JavaScriptCore
相關(guān)的幾個類

/*
  JS執(zhí)行的環(huán)境,同時也通過JSVirtualMachine管理著所有對象的生命周期,每個JSValue都和JSContext相關(guān)聯(lián)并且強引用context。
*/
#import "JSContext.h"
/*
JS對象在JSVirtualMachine中的一個強引用,其實就是Hybird對象。我們對JS的操作都是通過它。并且每個JSValue都是強引用一個context。同時,OC和JS對象之間的轉(zhuǎn)換也是通過它
*/
#import "JSValue.h"
/*
JS和OC對象的內(nèi)存管理輔助對象。由于JS內(nèi)存管理是垃圾回收,并且JS中的對象都是強引用,而OC是引用計數(shù)。如果雙方相互引用,勢必會造成循環(huán)引用,而導(dǎo)致內(nèi)存泄露。我們可以用JSManagedValue保存JSValue來避免。
*/
#import "JSManagedValue.h"
/*
JS運行的虛擬機,有獨立的堆空間和垃圾回收機制。
*/
#import "JSVirtualMachine.h"
/*
一個協(xié)議,如果JS對象想直接調(diào)用OC對象里面的方法和屬性,那么這個OC對象只要實現(xiàn)這個JSExport協(xié)議就可以了。
*/
#import "JSExport.h"

要求: 加載 html 頁面,點擊頁面上的按鈕時,監(jiān)聽按鈕的點擊,實現(xiàn)自己的 OC 方法,
首先在本地有個 html 文件

<!DOCTYPE html>
<html>
<head lang='zh'>
<meta charset="UTF-8">
    <script type="text/javascript" src="index1.js"></script>
</head>
<body>
<button onclick="hello()">點擊我彈出hello</button>
</body>
</html>

需要執(zhí)行的代碼
- (void)viewDidLoad {
[super viewDidLoad];

NSString *path = [[NSBundle mainBundle] bundlePath];
NSURL *url = [NSURL fileURLWithPath:path];

NSString *htmlpath = [[NSBundle mainBundle] pathForResource:@"index1" ofType:@"html"];
NSString *htmlCont = [NSString stringWithContentsOfFile:htmlpath encoding:NSUTF8StringEncoding error:nil];
[self.webView loadHTMLString:htmlCont baseURL:url];
self.webView.delegate = self;
}
#pragma mark - UIWebViewDelegate
- (void)webViewDidFinishLoad:(UIWebView *)webView{
JSContext *context = [self.webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
context[@"hello"] = ^{
    NSLog(@"哈哈哈哈哈哈啊哈哈");
    self.view.backgroundColor = [UIColor greenColor];
    UIAlertController *aler = [UIAlertController alertControllerWithTitle:@"點擊了js按鈕" message:@"message" preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *alertaction = [UIAlertAction actionWithTitle:@"確定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {   
    }];  
    [aler addAction:alertaction];
    [self presentViewController:aler animated:YES completion:nil];
};
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容