requestAccessToEntity iOS6-向后兼容性 – EKEventStore

以下iOS6的eventKit和新的隐私设置我使用下面的代码 – 这在iOS6设备上工作得很好。

不过,我希望相同的代码也适用于iOS 5.x的设备,我不希望两次写“相同的代码” – 看起来是错误的。

谁能协助一个优雅的解决scheme

EKEventStore *eventStore = [[EKEventStore alloc] init]; [eventStore requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError *error) { // some code }]; 

我正在使用这个:

 void (^addEventBlock)(); addEventBlock = ^ { NSLog(@"Hi!"); }; EKEventStore *eventStore = [[UpdateManager sharedUpdateManager] eventStore]; if ([eventStore respondsToSelector:@selector(requestAccessToEntityType:completion:)]) { [eventStore requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError *error) { if (granted) { addEventBlock(); } else { NSLog(@"Not granted"); } }]; } else { addEventBlock(); } 

我认为应该减less代码重复。

如果使用EKEventEditViewController在一个modalviewcontroller中显示事件,iOS会自动显示一个视图,说明拒绝权限时该怎么做。 所以,我这样做:

在viewDidLoad中:

 eventStore = [[EKEventStore alloc] init]; 

在用于添加事件的方法中:

 if ([eventStore respondsToSelector:@selector(requestAccessToEntityType:completion:)]) { __block typeof (self) weakSelf = self; // replace __block with __weak if you are using ARC [eventStore requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError *error) { if (granted) { [weakSelf performSelectorOnMainThread:@selector(addEventToCalendar) withObject:nil waitUntilDone:YES]; } else { NSLog(@"Not granted"); } }]; } else { [self addEventToCalendar]; } 

我有一个EventUtil.m文件

 +(void)proxyForIOS6EventKitToCallFunction:(SEL)function WithViewController:(UIViewController*)viewController { #pragma clang diagnostic push #pragma clang diagnostic ignored "-Warc-performSelector-leaks" AppDelegate *app = (AppDelegate*)[[UIApplication sharedApplication] delegate]; if([app.eventStore respondsToSelector:@selector(requestAccessToEntityType:completion:)]) { // For iOS 6 MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:viewController.view animated:YES]; hud.labelText = @""; //invoke requestAccessToEntityType... [app.eventStore requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError *error) { //Handle the response here… //Note: If you prompt the user, make sure to call the main thread if (granted == YES) { dispatch_async(dispatch_get_main_queue(), ^{ [viewController performSelector:function]; }); } }]; } else { [viewController performSelector:function]; } #pragma clang diagnostic pop } 

在我想要访问日历的视图控制器中,我导入EventUtil.h文件并调用这个函数:

 [EventUtil proxyForIOS6EventKitToCallFunction:@selector(displayModifyCalendarAlertView) WithViewController:self]; 

displayModifyCalendarAlertView是我想调用的function,如果日历的权限(iOS6或iOS <6)。