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

人已赞赏
iOS文章

iOS如何在ios中运用core animation暂停和继续动画

2021-1-14 19:31:30

iOS文章

IOS原子属性atomic和非原子属性nonatomic

2021-1-14 20:24:45

0 条回复 A文章作者 M管理员
    暂无讨论,说说你的看法吧
个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索