在完成块中调用时,UIAlertView需要很长时间才能显示

Bri*_*ian 3 uialertview ios ekeventstore

我的应用程序的一部分需要日历访问,这需要从iOS 7开始调用该EKEventStore方法-(void)requestAccessToEntityType:(EKEntityType)entityType completion:(EKEventStoreRequestAccessCompletionHandler)completion.

我添加了请求,如果用户选择允许访问,一切都会顺利运行,但如果用户拒绝或先前拒绝访问,则会出现问题.我添加了一个UIAlertView来通知用户访问是否被拒绝,但是UIAlertView一直需要20-30秒才能显示,并且在此期间完全禁用了UI.调试显示[alertView show]在延迟之前运行,即使它在延迟之后实际上没有显示.

为什么会出现这种延迟?如何将其删除?

[eventStore requestAccessToEntityType:EKEntityTypeEvent
                           completion:^(BOOL granted, NSError *error) {
                               if (granted) {
                                   [self createCalendarEvent];
                               } else {
                                   UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Calendar Access Denied"
                                                                                       message:@"Please enable access in Privacy Settings to use this feature."
                                                                                      delegate:nil
                                                                             cancelButtonTitle:@"OK"
                                                                             otherButtonTitles:nil];
                                   [alertView show];
                               }
                           }];
Run Code Online (Sandbox Code Playgroud)

Bri*_*ian 12

[alertView show]它不是线程安全的,因此它将UI更改添加到从中调度完成块的队列而不是主队列.我通过添加dispatch_async(dispatch_get_main_queue(), ^{});完成块内的代码解决了这个问题:

[eventStore requestAccessToEntityType:EKEntityTypeEvent
                           completion:^(BOOL granted, NSError *error) {
                               dispatch_async(dispatch_get_main_queue(), ^{
                                   if (granted) {
                                       [self createCalendarEvent];
                                   } else {
                                       UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Calendar Access Denied"
                                                                                           message:@"Please enable access in Privacy Settings to use this feature."
                                                                                          delegate:nil
                                                                                 cancelButtonTitle:@"OK"
                                                                                 otherButtonTitles:nil];
                                       [alertView show];
                                   }
                               });
                           }];
Run Code Online (Sandbox Code Playgroud)

  • 文档在此明确说明:"当用户点击授予或拒绝访问时,将在任意队列上调用完成处理程序." 这意味着"这可能是一个后台线程!" (3认同)