OC中與html文件中的交互操作

簡單整理下在Oc編譯環(huán)境下如何與html文件進行交互,本文介紹兩種比較簡單的交互方式

1.使用UIWebview代理方法攔截Url 
2.使用JavaScriptCore框架進行操作

第一種方法 —— 攔截UIWebview中url
1.導入html文件,并進行相關(guān)編寫操作


B4EEE6A0-D302-48C7-8201-A2F4E2EF52B1.png

2.加載UIWebView并設置代理

 // 找到本地html文件并加載UIWebView
    _webView.backgroundColor = [UIColor redColor];
    _webView.delegate = self;
    NSString *path = [[NSBundle mainBundle] pathForResource:@"First" ofType:@"html"];
    NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:path]];
    [_webView loadRequest:request];

3.交互操作
1.調(diào)用JS

 NSString *jsStr = [NSString stringWithFormat:@"showAlert('%@')",@"這里是JS中alert彈出的message"];
    [_webView stringByEvaluatingJavaScriptFromString:jsStr];
// 向js方法中傳入?yún)?shù)時,方法名不能寫錯 showAlert

2.代理方法攔截Url

#pragma mark - UIWebViewDelegate HTMl 交互OC
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{

    NSURL * url = [request URL];
    // url ==>firstclick://shareClick?title=%E5%88%86%E4%BA%AB%E7%9A%84%E6%A0%87%E9%A2%98&content=%E5%88%86%E4%BA%AB%E7%9A%84%E5%86%85%E5%AE%B9&url=%E9%93%BE%E6%8E%A5%E5%9C%B0%E5%9D%80&imagePath=%E5%9B%BE%E7%89%87%E5%9C%B0%E5%9D%80
   if ([[url scheme] isEqualToString:@"firstclick"]) {
       // [url scheme] ==> firstclick
        NSArray *params =[url.query componentsSeparatedByString:@"&"];
        
        NSMutableDictionary *tempDic = [NSMutableDictionary dictionary];
        for (NSString *paramStr in params) {
            NSArray *dicArray = [paramStr componentsSeparatedByString:@"="];
            if (dicArray.count > 1) {
                NSString *decodeValue = [dicArray[1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
                [tempDic setObject:decodeValue forKey:dicArray[0]];
            }
        }
       UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"方式一" message:@"這是OC原生的彈出窗" delegate:self cancelButtonTitle:@"收到" otherButtonTitles:nil];
       [alertView show];
       /*
        把從js文件中拿到的數(shù)據(jù)分割處理成字典,保存到本地
        拿到js中的內(nèi)容tempDic:{
        content = "\U5206\U4eab\U7684\U5185\U5bb9";
        imagePath = "\U56fe\U7247\U5730\U5740";
        title = "\U5206\U4eab\U7684\U6807\U9898";
        url = "\U94fe\U63a5\U5730\U5740";
        }

        */
       NSLog(@"拿到js中的內(nèi)容tempDic:%@",tempDic);
        return NO;
    }
    
    return YES;
}

第二種方法 —— JavaScriptCore框架進行操作
1.導入html文件


1.png

2.導入JavaScriptCore.framework框架,并在項目導入頭文件


導入框架.png
導入頭文件.png

3.找到本地html文件加載UIWebview

 NSString *path = [[NSBundle mainBundle] pathForResource:@"Second" ofType:@"html"];
    NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:path]];
    [_webView loadRequest:request];

4.關(guān)鍵步驟 —— 交互操作

 // 1.獲取運行環(huán)境
    JSContext *context = [self.webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    //2.定義好JS要調(diào)用的方法, share就是調(diào)用的share方法名
    context[@"share"] = ^() {
        NSLog(@"+++++++Begin Log+++++++");
        NSArray *args = [JSContext currentArguments]; // 找到所用對應的參數(shù)內(nèi)容
        
        dispatch_async(dispatch_get_main_queue(), ^{
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"方式二" message:@"這是OC原生的彈出窗" delegate:self cancelButtonTitle:@"收到" otherButtonTitles:nil];
            [alertView show];
        });
       
        // 3.列舉出該方法中的JavaScript對象
        for (JSValue *jsVal in args) {
            NSLog(@"%@", jsVal.toString);
        }
        
        NSLog(@"-------End Log-------");
    };

調(diào)用JS中的方法

 JSContext *context = [self.webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    NSString *textJS = @"showAlert('這里是JS中alert彈出的message')";
    [context evaluateScript:textJS];

以上簡單整理JS與OC交互的相關(guān)操作。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

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

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