2014-10-02 57 views
1

我正在嘗試在iOS上創建本地日曆。我請求訪問EKEntityTypeEvent並授予它,從EKEventStore(是的,我請求訪問的同一個實例)創建日曆,找到EKSourceTypeLocal,然後將其設置在我的新日曆上。致電saveCalendar:commit:error(與commit:YES)返回YES並且沒有NSError。生成的日曆分配有calendarIdentifier無法在iOS上創建本地日曆

但是當我翻轉到iOS日曆應用程序時,我的日曆不在那裏!我嘗試過iOS 7和8模擬器(在「重置內容和設置...」之後,因此沒有配置iCloud),並且在與iOS 8連接的iCloud iPhone 5s上運行。沒有任何效果!

我錯過了什麼?

我創建了一個光禿禿的項目有以下視圖控制器來說明這個問題:

@import EventKit; 
#import "ViewController.h" 

@interface ViewController() 

@property (weak, nonatomic) IBOutlet UILabel *resultLabel; 

@property (nonatomic, assign) NSUInteger calendarCount; 
@property (nonatomic, strong) EKEventStore *eventStore; 

@end 

@implementation ViewController 

- (void)viewDidLoad { 
    [super viewDidLoad]; 
    // Do any additional setup after loading the view, typically from a nib. 

    self.resultLabel.text = @"";   
    self.eventStore = [[EKEventStore alloc] init]; 
} 

- (IBAction)userDidTapCreateCalendar:(id)sender { 
    EKAuthorizationStatus status = [EKEventStore authorizationStatusForEntityType:EKEntityTypeEvent]; 

    if (status == EKAuthorizationStatusNotDetermined) { 
     __weak typeof(self) weakSelf = self; 
     [self.eventStore requestAccessToEntityType:EKEntityTypeEvent 
             completion:^(BOOL granted, NSError *error) { 
              if (granted) { 
               [weakSelf createCalendar]; 
              } else { 
               weakSelf.resultLabel.text = @"If you don't grant me access, I've got no hope!"; 
              } 
             }]; 
    } else if (status == EKAuthorizationStatusAuthorized) { 
     [self createCalendar]; 
    } else { 
     self.resultLabel.text = @"Access denied previously, go fix it in Settings."; 
    } 
} 

- (void)createCalendar 
{ 
    EKCalendar *calendar = [EKCalendar calendarForEntityType:EKEntityMaskEvent eventStore:self.eventStore]; 
    calendar.title = [NSString stringWithFormat:@"Calendar %0lu", (unsigned long)++self.calendarCount]; 

    [self.eventStore.sources enumerateObjectsUsingBlock:^(EKSource *source, NSUInteger idx, BOOL *stop) { 
     if (source.sourceType == EKSourceTypeLocal) { 
      calendar.source = source; 
      *stop = YES; 
     } 
    }]; 

    NSError *error = nil; 
    BOOL success = [self.eventStore saveCalendar:calendar commit:YES error:&error]; 
    if (success && error == nil) { 
     self.resultLabel.text = [NSString stringWithFormat:@"Created \"Calendar %0lu\" with id %@", 
           (unsigned long)self.calendarCount, calendar.calendarIdentifier]; 
    } else { 
     self.resultLabel.text = [NSString stringWithFormat:@"Error: %@", error]; 
    } 
} 

@end 

回答

1

我測試過的設備上的代碼,它的工作原理確定(改變EKEntityMaskEvent - >EKEntityTypeEvent)。我可以在iOS日曆中看到新的日曆。 看起來像模擬器實際上並沒有保存你的日曆。前段時間我有同樣的問題。

+0

當然就是這樣。它乞丐認爲,這甚至編譯。 _但動態語言太棒了! – 2014-10-03 08:19:22