我正在使用扫描蓝牙设备的方法,我从另一个框架导入。扫描方法需要一段时间,它会阻止GUI,这是我们从未想过的。
我也有MBProgressHud,试图在扫描时显示一个hud,但它没有工作(hud没有显示)。有什么帮助吗?
以下是我目前正在使用的代码:
[hud showAnimated:YES whileExecutingBlock:^{
self.btDevices = [Util scanBT];
}];
编辑1:好的,所以如果我使用这段代码,它会暂时阻止我的用户界面,然后突然继续运行。
hud = [[MBProgressHUD alloc] initWithView:self.view];
hud.labelText = @"Now scanning";
hud.dimBackground = YES;
hud.opacity = 0.5;
[hud show:YES];
[hud hide:YES afterDelay:5.0];
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.001 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void){
self.btDevices = [Util scanBT];
});
编辑2:好的,我将发布我的所有代码块:
hud = [[MBProgressHUD alloc] initWithView:[self getTopView:self.view]];
hud.labelText = @"Now scanning";
hud.dimBackground = YES;
hud.opacity = 0.5;
[hud showAnimated:YES whileExecutingBlock:^{
self.btDevices = [Util scanBT];
}];
dispatch_queue_t myqueue = dispatch_queue_create("queue", NULL);
dispatch_async(myqueue, ^{
//Whatever is happening in the BT scanning method will now happen in the background
dispatch_async(dispatch_get_main_queue(), ^{
[MBProgressHUD hideHUDForView:[self getTopView:self.view] animated:YES];
});
});
/** Recursion to get the top most view in view layer. */
- (UIView *)getTopView:(UIView *)view
{
if ([view.superview class]) {
return [self getTopView:view.superview];
}
return view;
}
我请求在弹出框中扫描bt,但是我想在主视图中显示HUD,所以我写了一个块来检索主视图。也许这就是问题发生的地方?
答案 0 :(得分:1)
试试这个:
在viewDidload或您要放置它的方法
MBProgressHUD *hud = [[MBProgressHUD alloc] initWithView:self.view];
[hud setDimBackground:YES];
[hud setOpacity:0.5f];
[hud show:YES];
[hud hide:YES afterDelay:5.0];
[self performSelector:@selector(startScanning) withObject:nil afterDelay:5.0];
和你的方法
- (void) startScanning {
self.btDevices = [Util scanBT];
}
或者我认为你应该尝试运行
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.001 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void){
// Insert task code here
self.btDevices = [Util scanBT];
});
尝试使用完成块
[hud showAnimated:YES whileExecutingBlock:^{
self.btDevices = [Util scanBT];
} completionBlock:^{
//code for after completion
}];
或者你也可以试试这个
[MBProgressHUD showHUDAddedTo:self.view animated:YES];
dispatch_queue_t myqueue = dispatch_queue_create("queue", NULL);
dispatch_async(myqueue, ^{
//Whatever is happening in the BT scanning method will now happen in the background
self.btDevices = [Util scanBT];
dispatch_async(dispatch_get_main_queue(), ^{
[MBProgressHUD hideHUDForView:self.view animated:YES];
});
});