iOS使用MBProgressHUD出現(xiàn)的坑

問題一:

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

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容