- (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"]; });
相關文章: