【发布时间】:2016-05-27 17:04:44
【问题描述】:
Xcode 版本:7.2.1,iOS 版本:9.1+
我正在尝试在 iPad 上显示 UIAlertController 警报消息,该消息显示“正在加载...请稍候”消息,上面没有任何按钮。我在开始长操作之前呈现 UIAlertController,然后在长操作之后关闭 UIAlertController。 但是,正在发生的事情是 UIAlertController 不会立即出现。它只会在较长的操作完成后短暂闪烁,然后消失。
以下是一般代码结构:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Loading" message:@"Please wait...\n\n\n" preferredStyle:UIAlertControllerStyleAlert];
[self presentViewController:alert animated:YES completion:nil];
/// Perform long operation here...
/// (Basically, a message is being sent to a server, a long operation happens on
/// the server, and then the server returns a response to the iPad client.)
[alert dismissViewControllerAnimated:YES completion:nil];
}
我尝试了许多替代方法,例如使用 dispatch_async 以便在长操作发生时可以同时显示警报消息:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Loading Dataset" message:@"Please wait...\n\n\n" preferredStyle:UIAlertControllerStyleAlert];
[self presentViewController:alert animated:YES completion:nil];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
/// Perform long operation here...
dispatch_async(dispatch_get_main_queue(), ^{
[alert dismissViewControllerAnimated:YES completion:nil];
});
});
}
我尝试过单独使用 UIAlertView(我知道它在 iOS 8 中已被弃用),但也不管用。
我尝试将长操作代码包装在 performSelector 消息中,但无济于事。
过去,在这种情况下,使用带有 dispatch_queue 的 UIAlertView 可以无缝地工作。
感谢任何帮助。
编辑:
需要注意的一件有趣的事情:在 dispatch_async 代码中,如果我在调用长操作代码之前添加一个 usleep(250000),大约 80% 的时间,UIAlertController 警报消息将在正确的时间显示:BEFORE漫长的操作开始了。然而,这不是 100% 的时间,也不是一个可持续的解决方案。用较小的号码调用 usleep 不起作用。
请注意,对于 DISPATCH_QUEUE_PRIORITY_DEFAULT 选项,我也尝试过: DISPATCH_QUEUE_PRIORITY_HIGH、DISPATCH_QUEUE_PRIORITY_LOW 和 DISPATCH_QUEUE_PRIORITY_BACKGROUND
而且,我也尝试了以下方法:
dispatch_queue_t myQueue = dispatch_queue_create(NULL, DISPATCH_QUEUE_CONCURRENT);
dispatch_async(myQueue, ^{
/// Perform long operation here...
dispatch_async(dispatch_get_main_queue(), ^{
[alert dismissViewControllerAnimated:YES completion:nil];
});
});
【问题讨论】:
-
您的第二个变体是正确的,您应该发布更多关于您的长期操作的代码。您可能在长操作中的某处阻塞了主线程。这会导致这个问题。
-
@Sulthan 是的,在长操作代码中,我使用 TCP 套接字来 send 和 recv 数据。 recv 套接字函数会阻塞,直到它从服务器接收到数据。
-
你是在后台线程上做的(在第二个版本中),所以这应该不是问题。我猜你也不知何故阻塞了那里的主线程。
标签: ios9 uialertview uialertcontroller