詳情請看代碼的注釋,
iOS 6.0以上系統,應用對於事件的操作都要獲得用戶的允許,這和之前的系統版本不同,SDK也有相應的變化。
[eventDB requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError *error) {
// handle access here
}];
EKEventStore *eventDB = [[EKEventStore alloc] init];
NSInteger countNum = [celendarArray count];
__block NSInteger curNum = 0;
[eventDB requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError *error) {
// handle access here
if (granted == YES) {
for (NSDictionary *celendar in celendarArray){
EKEvent *myEvent = [EKEvent eventWithEventStore:eventDB];
NSDate *StartDate = [NSDate dateWithTimeIntervalSince1970:[[[celendar objectForKey:@"btime"] substringToIndex:10] longLongValue]];
NSDate *EndDate = [NSDate dateWithTimeIntervalSince1970:[[[celendar objectForKey:@"etime"] substringToIndex:10] longLongValue]];
myEvent.title = [celendar objectForKey:@"title"];
myEvent.startDate = StartDate;
myEvent.endDate = EndDate;
myEvent.allDay = [[celendar objectForKey:@"allday"] integerValue];
NSString *addr = [celendar objectForKey:@"addr"];
myEvent.location = addr == NULL ? @"":addr;
NSString *explain =[celendar objectForKey:@"explain"];
myEvent.notes = explain == NULL ? @"":explain;
[myEvent setCalendar:[eventDB defaultCalendarForNewEvents]];
NSError *err;
//commit:yes為單挑插入, commit:NO為批量插入,需要再最後執行[eventDB commit:nil]
[eventDB saveEvent:myEvent span:EKSpanThisEvent commit:NO error:&err];
++curNum;
}
}
}];
//用戶交互的時候,可以提示進行的進度
while (curNum < countNum) {
NSLog(@"curNum = %d, contNum = %d", curNum, countNum);
continue;
}
[eventDB commit:nil];
[eventDB release];