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

时间:2014-03-11 18:31:41

标签: ios uialertview ekeventstore

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

我添加了请求,如果用户选择允许访问,一切都会顺利运行,但如果用户拒绝或先前已拒绝访问,则会出现问题。我添加了UIAlertView来通知用户访问是否被拒绝,但UIAlertView始终需要20-30秒才能显示,并在此期间完全禁用用户界面。调试显示[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];
                               }
                           }];

1 个答案:

答案 0 :(得分: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];
                                   }
                               });
                           }];