問題一:
(“MBProgressHUD needs to be accessed on the main thread.”)
我用webView加載H5頁面,并在webViewDelegate方法中使用MBProgressHUD控件,如下:
-(void)webViewDidStartLoad:(UIWebView *)webView
[self showLoadHUDMsg:@"正在加載..."];
}
-(void)webViewDidFinishLoad:(UIWebView *)webView{
[self hideLoadHUD];
}
但是,當(dāng)我在webView中使用js交互push到下一個頁面后,出現(xiàn)下列報錯:(present到下一個頁面卻不會出現(xiàn)報錯)
*** Terminating app due to uncaught exception ‘NSInternalInconsistencyException‘, reason: ‘MBProgressHUD needs to be accessed on the main thread.‘
‘MBProgressHUD needs to be accessed on the main thread.‘這個錯誤主要翻譯成,MBProgressHUD必須在主線程上運行。
解決辦法:
//充值繳費
-(void)recharge{
// present卻不會出現(xiàn)問題
// JXSRechargeVC *rechangeVC = [JXSRechargeVC new];
// UINavigationController *nvi = [[UINavigationController alloc]initWithRootViewController:rechangeVC];
// [self presentViewController:nvi animated:YES completion:nil];
NSLog(@"線程1--->%d",[NSThread isMainThread]);
dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
NSLog(@"線程2--->%d",[NSThread isMainThread]);
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"線程3--->%d",[NSThread isMainThread]);
JXSRechargeVC *rechangeVC = [JXSRechargeVC new];
[self.navigationController pushViewController:rechangeVC animated:YES];
});
});
}
線程的打印結(jié)果如下:

0DCC7C1F-B5A0-44D8-AAD0-E07EC70BBDA6.png
問題二:
顯示NSAssert(view, @"View must not be nil.")錯誤提示
我添加MBProgressHUD是使用的分類,將HUD顯示在window上面,關(guān)鍵代碼如下:
//隱藏加載提示
- (void)hideLoadHUD{
[MBProgressHUD hideAllHUDsForView:[self window] animated:YES];
}
//正在加載提示
- (void)showLoadHUDMsg:(NSString *)msg{
MBProgressHUD *progressHUD = [MBProgressHUD showHUDAddedTo:[self window] animated:YES];
progressHUD.labelText = msg;
//progressHUD.mode = MBProgressHUDModeText;
//progressHUD.dimBackground = YES;
}
-(UIWindow *)window{
return [UIApplication sharedApplication].keyWindow;
}
但是使用過程中會出現(xiàn)NSAssert(view, @"View must not be nil.")的錯誤提示,解決方法如下:([UIApplication sharedApplication].keyWindow替換[self window])
//隱藏加載提示
- (void)hideLoadHUD{
[MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];
}
//正在加載提示
- (void)showLoadHUDMsg:(NSString *)msg{
MBProgressHUD *progressHUD = [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow animated:YES];
progressHUD.labelText = msg;
//progressHUD.mode = MBProgressHUDModeText;
//progressHUD.dimBackground = YES;
}