iOS使用MBProgressHUD出现的坑

来源:互联网 发布:vscode写网页 编辑:程序博客网 时间:2024/05/20 19:32

问题一:

(“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]; }

但是,当我在webView中使用js交互push到下一个页面后,出现下列报错:(present到下一个页面却不会出现报错)

*** 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却不会出现问题//    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];        });    });}

线程的打印结果如下:


0DCC7C1F-B5A0-44D8-AAD0-E07EC70BBDA6.png

问题二:

显示NSAssert(view, @"View must not be nil.")错误提示

我添加MBProgressHUD是使用的分类,将HUD显示在window上面,关键代码如下:

//隐藏加载提示- (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;}

但是使用过程中会出现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;}


作者:来宝
链接:http://www.jianshu.com/p/c3035ca50eb2
來源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。