iOS开发 --- UIWebView OC调用JS方法

 

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationItem.title = @"活动详情页面";
    self.backButton.frame = CGRectMake(0, 0, 66, 44);
    [self.backButton setTitle:@"关闭" forState:UIControlStateNormal];
    [self.backButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    
    [self addWebView];
    
}

添加WebView 

-(void)addWebView{
    self.webView = [[UIWebView alloc]initWithFrame:CGRectMake(0, StatusAndNaviHeight, SCREEN_WIDTH, SCREEN_HEIGHT - StatusAndNaviHeight -iPhoneXSafeBottomMargin)];
    _webView.delegate = self;
    _webView.scalesPageToFit = YES;
    NSString *url = [OnlineServiceUrl stringByAppendingFormat:@"?tk=%@&ut=%@",[userDefa valueForKey:@"AppKey"],self.userTokenStr];
    //加载请求的时候忽略缓存
    NSURLRequest *request  = [NSURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:5.0];

    [_webView loadRequest:request];
    [self.view addSubview:_webView];
}

左上角返回按钮点击方法实现

-(void)leftButAction{

    NSString *jsStr = [NSString stringWithFormat:@"%@",@"isShowAlertView()"];
    NSString *result = [self.webView stringByEvaluatingJavaScriptFromString:jsStr];
    //js返回0:js控制跳出弹框 1:返回上级页面
    NSLog(@"jsStr:%@",result);
    
    if ([result intValue] == 1) {
        [self.navigationController popViewControllerAnimated:YES];
    }
}

注意:

stringByEvaluatingJavaScriptFromString  这个方法只能在主线程调用!!!

dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);  
dispatch_async(queue, ^{  
    [webView stringByEvaluatingJavaScriptFromString:@"aaa"];
});
//崩溃信息
Tried to obtain the web lock from a thread other than the main thread or the web thread. 
This may be a result of calling to UIKit from a secondary thread. Crashing now...

崩溃产生的原因是你在主线程以外的线程调用了UIKit,系统在执行stringByEvaluatingJavaScriptFromString的时候调用了UIKit里的一些方法,所以不允许在主线程之外的线程去调用这个方法。

解决方法也有很多可以用

[webView performSelectorOnMainThread:]
//或者
dispatch_async(dispatch_get_main_queue(), ^{  
    [webView stringByEvaluatingJavaScriptFromString:@"aaa"];
});        

 

相关文章:

ios--OC调用JS传递参数并获得返回值(实例)

iOS OC与JS互相调用带参数带返回值

UIWebView和WKWebView的使用及js交互

iOS开发-stringByEvaluatingJavaScriptFromString导致崩溃

实现OC与JS的交互

UIWebView & WKWebView 详解上

深入解析WebViewJavascriptBridge

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值