美文网首页
iOS利用webView实现 H5调用OC原生方法

iOS利用webView实现 H5调用OC原生方法

作者: 心在前方 | 来源:发表于2018-11-29 14:12 被阅读0次

前言

在VC中加载一个webView,实现其代理方法

@interface RealWebController ()<UIWebViewDelegate>
@property (nonatomic, strong) UIWebView *webView;
@property (nonatomic, assign) BOOL flag;
@property (nonatomic, strong) JSContext *jsContext;
@end

- (instancetype)initWithWebURL:(NSString *)url{
    self = [super init];
    if (self) {
        [self initializeUserInterface];
        self.webView = [[UIWebView alloc]init];
        [self.view addSubview:_webView];
        _webView.frame = CGRectMake(0, Screen_Ratio(64), ScreenWidth, ScreenHeight - 64); //设置位置
        _webView.delegate = self;
        _webView.scalesPageToFit = YES;
        //创建Request
        NSURLRequest *request = [NSURLRequest requestWithURL:url.jqURL];
        //加载网页
        [_webView loadRequest:request];
    }
    return self;
}
//监听到请求
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
    //这里的request就是你发送的请求,可以直接从里面取出请求地址,后面与js的交互也是通过这里监听js中window的location的改变,然后通过request中数出来进行相应的判断
    NSLog(@"监听到新的请求,请求地址是:%@------", request.URL.absoluteString);
    return YES;
}
//开始加载新的请求
- (void)webViewDidStartLoad:(UIWebView *)webView{
    [SVProgressHUD show];
    NSLog(@"01:开始加载请求------");
    }

//新的请求加载完成
- (void)webViewDidFinishLoad:(UIWebView *)webView{
    [SVProgressHUD dismiss];
    NSLog(@"02:请求加载完成------");
    self.jsContext = [self.webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    MJWeakSelf   //利用weakself,避免循环引用问题
    //请求加载完成后,通过jsContext,监听与H5约定的方法名:registyjf
    _jsContext[@"registyjf"] = ^() {
        //获取参数数组,参数类型为JSValue
        NSArray<JSValue *> *args = [JSContext currentArguments];
        NSString *code = args[0].toString;
        if ([code isEqualToString:@"EXECUTE_SUCCESS"]) {
            //如果有UI更新,必须在主线程中调用
            dispatch_async(dispatch_get_main_queue(), ^{
                //更新用户的注册状态
                USER.isyjfpay = @"1";
                NSMutableDictionary *dic = [[NSUserDefaults standardUserDefaults] objectForKey:@"userInfo"];
                [dic setObject:@"1" forKey:@"isyjfpay"];
                [[NSUserDefaults standardUserDefaults] setObject:dic forKey:@"userInfo"];
                [weakSelf popView];
            });
        }else{
            //失败,退出
            [weakSelf popView];
            
        }
        
    };
}

//加载出错

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{
    [SVProgressHUD showErrorWithStatus:@"加载失败" duration:3];
    NSLog(@"请求加载失败");
    
}

相关文章

网友评论

      本文标题:iOS利用webView实现 H5调用OC原生方法

      本文链接:https://www.haomeiwen.com/subject/lixfcqtx.html