iOS 与 js交互的其一方法 WebViewJavascriptBridge的使用

时间:2021-09-17 18:49:49

#import <WebViewJavascriptBridge.h>

///

 

@interface ZWBridgeViewController ()<WKNavigationDelegate, WKUIDelegate, UIGestureRecognizerDelegate>

 

@property (nonatomicstrong) ZWCommonNavBar *navBar;

@property (nonatomicstrong) WKWebView *webView;

@property (nonatomicstrong) WebViewJavascriptBridge *bridge;

@property (nonatomiccopy) NSString *urlStr;

@property (nonatomiccopy) NSString *webTitle;

@end

 

@implementation ZWBridgeViewController

 

- (instancetype)initWithParams:(NSDictionary *)params {

    self = [super init];

    if (self) {

        

    }

    return self;

}

 

 

- (void)viewDidAppear:(BOOL)animated

{

    [super viewDidAppear:animated];

    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {

        self.navigationController.interactivePopGestureRecognizer.delegate = self;

    }

}

- (void)viewWillDisappear:(BOOL)animated

{

    [super viewWillDisappear:animated];

    [SVProgressHUD dismiss];

    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {

        self.navigationController.interactivePopGestureRecognizer.delegate = nil;

    }

}

 

- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer

{

    return NO;

}

 

- (void)viewDidLoad {

    [super viewDidLoad];

    

    [SVProgressHUD show];

    

    NSLog(@"%@",self.urlStr);

    

    [self configNavBar];

    [self configWebView];

    [self configBridge];

    [self configBridgeRegister];

    [self configBridgeCallHander];

}

 

- (void)configNavBar {

    self.titlle = ""

}

 

- (void)configWebView {

    

    NSURL *url = [NSURL URLWithString:self.urlStr];

    NSURLRequest *request = [NSURLRequest requestWithURL:url];

    [self.webView loadRequest:request];

}

 

- (void)configBridge {

    

    // 开启日志

    [WebViewJavascriptBridge enableLogging];

    self.bridge = [WebViewJavascriptBridge bridgeForWebView:self.webView];

    [self.bridge setWebViewDelegate:self];

}

 

#pragma mark JS Call OC

- (void)configBridgeRegister {

    

    kWeakSelf(self);

    // 商品详情

    [self.bridge registerHandler:@"func" handler:^(id data, WVJBResponseCallback responseCallback) {

        

        NSDictionary *params = data;

        NSDictionary *dic = @{

                              @"goodsId" : @([params[@"productId"] integerValue])

                              };

        UIViewController *vc = 

        [weakself.navigationController pushViewController:vc animated:YES];

    }];

    

    [self.bridge registerHandler:@"nativeHomePage" handler:^(id data, WVJBResponseCallback responseCallback) {

        [weakself zw_toHomeRootViewController];

    }];

    

    [self.bridge registerHandler:@"nativeGoback" handler:^(id data, WVJBResponseCallback responseCallback) {

        [weakself.navigationController popviewcontroller]

    }];

    

    [self.bridge registerHandler:@"nativeOrderList" handler:^(id data, WVJBResponseCallback responseCallback) {

        

        NSDictionary *params = @{

                                 @"index" : @(0)

                                 };

        UIViewController *vc = [[CTMediator sharedInstance] ymd_mediator_MyOrderViewControllerWithParams:params];

        [weakself.navigationController pushViewController:vc animated:YES];

        

        BOOL closePage = [data[@"closePage"] integerValue];

        if (closePage) {

            NSMutableArray *mArray = [NSMutableArray arrayWithArray: weakself.navigationController.viewControllers];

            [mArray removeObjectAtIndex: weakself.navigationController.viewControllers.count - 2];

            weakself.navigationController.viewControllers = [NSArray arrayWithArray: mArray];

        }

    }];

    

    [self.bridge registerHandler:@"nativeOrderListDetail" handler:^(id data, WVJBResponseCallback responseCallback) {

        NSDictionary *resultData = data[@"resultData"];

        NSDictionary *dic = @{

                              @"orderId" : @([resultData[@"orderId"] integerValue])

                              };

        UIViewController *vc = [[CTMediator sharedInstance] ymd_mediator_MyOrderDetailViewControllerWithParams:dic];

        [self.navigationController pushViewController:vc animated:YES];

        

        BOOL closePage = [data[@"closePage"] integerValue];

        if (closePage) {

            NSMutableArray *mArray = [NSMutableArray arrayWithArray: weakself.navigationController.viewControllers];

            [mArray removeObjectAtIndex: weakself.navigationController.viewControllers.count - 2];

            weakself.navigationController.viewControllers = [NSArray arrayWithArray: mArray];

        }

    }];

    

    [self.bridge registerHandler:@"nativeShare" handler:^(id data, WVJBResponseCallback responseCallback) {

        NSDictionary *resultData = data[@"resultData"];

 

        ZWFreeOrderShareVC *vc = [[ZWFreeOrderShareVC alloc] init];

 

        vc.shareModel = shareModel;

        [self.navigationcontroller push:vc animate:ture]

    }];

    

    [self.bridge registerHandler:@"nativeDominosDetail" handler:^(id data, WVJBResponseCallback responseCallback) {

        NSDictionary *resultData = data[@"resultData"];

        

//        NSDictionary *relayParams = @{

//                                      @"dominosId" : @([resultData[@"dominosId"] integerValue]),

//                                      @"dominosOrderId" : @([resultData[@"dominosOrderId"] integerValue]),

//                                      @"type" : @(1)

//                                      };

 

        NSDictionary *userInfo = @{

                                   @"dominosOrderId" : @([resultData[@"dominosOrderId"] integerValue]),

                                   };

        

        [[NSNotificationCenter defaultCenter] postNotificationName:kZWFreeOderSuccessNotification object:nil userInfo:userInfo];

        NSMutableArray *mArray = [NSMutableArray arrayWithArray: self.navigationController.viewControllers];

        [mArray removeObjectAtIndex: self.navigationController.viewControllers.count - 1];

        self.navigationController.viewControllers = [NSArray arrayWithArray: mArray];

   //[self.navigationcontroller push:vc animate:ture]

    }];

}

 

#pragma mark OC Call JS

- (void)configBridgeCallHander {

    

    [self.bridge callHandler:@"ocCallJs" data:@{@"name": @"James call"} responseCallback:^(id responseData) {

        

    }];

}

 

#pragma mark WKNavigationDelegate

- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {

    [webView evaluateJavaScript:@"document.documentElement.style.webkitUserSelect=‘none‘;" completionHandler:nil];

    [webView evaluateJavaScript:@"document.documentElement.style.webkitTouchCallout=‘none‘;" completionHandler:nil];

    [SVProgressHUD dismiss];

}

 

#pragma mark KVO

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{

    if ([keyPath isEqualToString:@"title"]) {

        if (object == self.webView) {

            self.navBar.title = self.webView.title;

        } else {

            [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];

        }

    } else {

        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];

        

    }

}

 

 

#pragma mark Lazy

- (WKWebView *)webView {

    if (!_webView) {

        _webView = [[WKWebView alloc] init];

        _webView.navigationDelegate = self;

        _webView.UIDelegate = self;

        [_webView addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:NULL];

        [self.view addSubview:_webView];

        [_webView mas_makeConstraints:^(MASConstraintMaker *make) {

            make.edges.mas_equalTo(UIEdgeInsetsMake(k_Height_NavBar, 0, 0, 0));

        }];

    }

    return _webView;

}