iOS js与原生交互

WKWebView的实现

需求: 我们经常在项目中加载网页,但是点击网页的事件需要调用本地OC代码


1、配置WKWebView

- (void)initWKWebView

{

    NSString *hidenNavAndTabScript = @"$(document).ready(function(){$(\"#canvasBg\").css('top','0');$(\"#header\").hide();$(\"#header\").next().hide();$(\"#footer\").hide();});$(\"#gund\").css('top','0');$(\".diymenu\").hide();$(\".fui-content\").css('bottom','0').css('padding-bottom', '0')";

    //WKUserScriptInjectionTimeAtDocumentEnd为网页加载完成时注入

    WKUserScript *script = [[WKUserScript alloc] initWithSource:hidenNavAndTabScript injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];

    //根据生成的WKUserScript对象,初始化WKWebViewConfiguration

    WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];

         WKPreferences*preferences = [WKPreferencesnew];

         preferences.javaScriptCanOpenWindowsAutomatically = YES;

         configuration.preferences= preferences;

    [configuration.userContentControlleraddUserScript:script];

    self.webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, kDeviceWidth, kDeviceHeight-kNavHeight) configuration:configuration];

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:self.infoUrl]];

    [requestsetValue:@"www.suxiangshidai.com://" forHTTPHeaderField:@"Referer"];

    [self.webViewloadRequest:request];

    self.webView.UIDelegate = self;

    self.webView.navigationDelegate = self;

    [self.viewaddSubview:self.webView];

}

2、JS调用OC

2.1 、 //意思是网页中需要传递的参数是通过这个JS中的showMessage方法来传递的

- (void)viewWillAppear:(BOOL)animated

{

    [superviewWillAppear:animated];

    [self.webView.configuration.userContentController addScriptMessageHandler:self name:@"ScanAction"];

    [self.webView.configuration.userContentController addScriptMessageHandler:self name:@"CustomerServiceChatAction"];

    [self.webView.configuration.userContentController addScriptMessageHandler:self name:@"saveImageToAlbum"];

    [self.webView.configuration.userContentController addScriptMessageHandler:self name:@"saveMultImages"];

}

- (void)viewWillDisappear:(BOOL)animated

{

    [super viewWillDisappear:animated];

    // 因此这里要记得移除handlers

    [self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"ScanAction"];

    [self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"CustomerServiceChatAction"];

    [self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"saveImageToAlbum"];

    [self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"saveMultImages"];

}

2.2、代理二:接收JS端发过来的消息,并处理相应的业务逻辑,

#pragma mark - WKScriptMessageHandler

- (void)userContentController:(WKUserContentController*)userContentController didReceiveScriptMessage:(WKScriptMessage*)message

{

    NSLog(@"body:%@",message.body);

    if([message.nameisEqualToString:@"ScanAction"]) {

        [selfscanEvent];

    }else if ([message.name isEqualToString:@"CustomerServiceChatAction"]){

        [self CustomerServiceChatAction:message.body];

    }elseif([message.nameisEqualToString:@"saveImageToAlbum"]){

        [self saveImageToAlbum];

        NSLog(@"saveImageToAlbum");

    }elseif([message.nameisEqualToString:@"saveMultImages"]){

        [selfsaveMultImages:message.body];

    }

}

3、OC调用JS

3.1、动态注入js方法

- (void)evaluateJavaScript:(NSString*)javaScriptString completionHandler:(void(^ _Nullable)(_Nullableid,NSError* _Nullable error))completionHandler;

// 此处是设置需要调用的js方法以及将对应的参数传入,需要以字符串的形式NSString*jsFounction = [NSStringstringWithFormat:@"getAppConfig('%@')", APP_CHANNEL_ID];// 

调用API方法

[self.weexWebView evaluateJavaScript:jsFounction completionHandler:^(idobject,NSError* _Nullable error) {

NSLog(@"obj:%@---error:%@", object, error); 

 }];

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容