iOS使用MBProgressHUD出现的坑

 
 

问题一:

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

猜你喜欢

转载自blog.csdn.net/qq_33226881/article/details/78819723