iOS_經(jīng)驗(yàn)(4)_js和oc交互(UI&WKWebView)

一丶說(shuō)明

推薦使用WKWebView

在性能、穩(wěn)定性
WKWebView更多的支持HTML5的特性
WKWebView更快,占用內(nèi)存可能只有UIWebView的1/3 ~ 1/4
WKWebView高達(dá)60fps的滾動(dòng)刷新率和豐富的內(nèi)置手勢(shì)
WKWebView具有Safari相同的JavaScript引擎
WKWebView增加了加載進(jìn)度屬性
將UIWebViewDelegate和UIWebView重構(gòu)成了14個(gè)類(lèi)與3個(gè)協(xié)議

WKWebView的學(xué)習(xí):http://www.itdecent.cn/p/7bb5f15f1daa

二丶 iOS調(diào)用js

WKWebView

用到方法:
- (void)evaluateJavaScript:(NSString *)javaScriptString completionHandler:(void (^ __nullable)(__nullable id, NSError * __nullable error))completionHandler;

例子:調(diào)用js的hello()方法,傳遞"我是被iOS調(diào)用"的參數(shù)

iOS方面;
[self.webView evaluateJavaScript:@"hello('我是被iOS調(diào)用的')" completionHandler:nil];

js方面

function hello(msg)
{
        document.write(msg);
}

UIWebView

iOS方法
   [self.webView stringByEvaluatingJavaScriptFromString:@"hello('我是被iOS調(diào)用的')"];
js:
 function hello(msg) {
   document.write(msg)
}

三丶js調(diào)用iOS

WKWebView

用到方法:
- (void)addScriptMessageHandler:(id <WKScriptMessageHandler>)scriptMessageHandler name:(NSString *)name;
例子:js點(diǎn)擊按鈕,調(diào)用iOS的hello_OC方法;傳遞參數(shù):{hello:1};

js代碼:

<input type="button" value="點(diǎn)擊觸發(fā)OC方法" onclick="window.webkit.messageHandlers.hello_OC.postMessage({hello:1})">

oc代碼:
1.代理
<WKScriptMessageHandler>
2.注入對(duì)象/方法
  WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
//這個(gè)方法會(huì)造成代理不會(huì)因?yàn)轫?yè)面消失而釋放:
// [config.userContentController addScriptMessageHandler:self name:@"hello_OC"];
使用(WeakScriptMessageDelegate 已經(jīng)封裝好了,可以直接使用)
  [config.userContentController addScriptMessageHandler:[[WeakScriptMessageDelegate alloc] initWithDelegate:self] name:@"hello_OC"];

self.webView = [[WKWebView alloc] initWithFrame:CGRectZero
                                      configuration:config];

3.
#pragma mark - WKScriptMessageHandler
- (void)userContentController:(WKUserContentController *)userContentController
      didReceiveScriptMessage:(WKScriptMessage *)message
{
    NSLog(@"<JS調(diào)用了 %@ 方法,參數(shù):%@>", message.name, message.body);
}
4.WeakScriptMessageDelegate

#import <Foundation/Foundation.h>
#import <WebKit/WebKit.h>

@interface WeakScriptMessageDelegate : NSObject<WKScriptMessageHandler>

@property (nonatomic, weak) id<WKScriptMessageHandler> scriptDelegate;

- (instancetype)initWithDelegate:(id<WKScriptMessageHandler>)scriptDelegate;

@end

@implementation WeakScriptMessageDelegate

- (instancetype)initWithDelegate:(id<WKScriptMessageHandler>)scriptDelegate
{
    self = [super init];
    if (self) {
        _scriptDelegate = scriptDelegate;
    }
    return self;
}

- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message
{
    [self.scriptDelegate userContentController:userContentController didReceiveScriptMessage:message];
}

@end

UIWebView

iOS方法:

#pragma mark - delegete
-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    NSLog(@"__>%s",__func__);
    NSLog(@"__>%@",request.URL.absoluteString);
    NSString *parameterStr = [[request.URL.absoluteString componentsSeparatedByString:@"parm:"] lastObject];
    NSDictionary *dict  = [parameterStr ZB_dictionaryWithURLString];
    NSLog(@"js調(diào)用oc,參數(shù)為:%@",dict);
    
    return YES;
}

js方面:
function toOC(argument) {
            /*UIWebVIew*/
            window.location.href = "parm:hello iOS"
}

function iOSShareApp(argument) {
            /*UIWebView*/
            window.location.href = "parm:shareTitle=hyd&shareDesc='副標(biāo)題'&shareUrl='分享跳轉(zhuǎn)的鏈接'&sharePic='www.hyd.com'"
        }

四丶注意

五丶github

https://github.com/k373379320/OCAndJs

成熟第三方:
https://github.com/marcuswestin/WebViewJavascriptBridge

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

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

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