关注iOS6 eventKit和新的隐私设置我使用以下代码 - 这在iOS6设备上完全正常。
尽管如此,我希望相同的代码也适用于iOS 5.x的设备,我希望不要两次写“相同的代码” - 似乎错了。
任何人都可以协助优雅的解决方案吗?
EKEventStore *eventStore = [[EKEventStore alloc] init];
[eventStore requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError *error) {
// some code
}];
答案 0 :(得分:9)
我正在使用它:
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();
}
我认为应该减少代码重复。
答案 1 :(得分:4)
如果您在带有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];
}
答案 2 :(得分:0)
我有一个带
的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是我要调用的函数,如果给出了日历权限(iOS6或iOS< 6)。