在 iOS 5 中,它可以正常工作,因为代码不在“块”代码中。在 iOS 6 或更高版本中,代码进入完成块,“addEventToCalendar”方法末尾的 if else 条件首先执行。有什么解决方法吗?我需要将警报标识符保存在数据库中
- (NSString *) addEventToCalendar
{
EKEventStore *eventStore = [[EKEventStore alloc] init];
__block int calChk = 0;
if ([eventStore respondsToSelector:@selector(requestAccessToEntityType:completion:)])
{
// ios 6 or newer
[eventStore requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError *error)
{
NSLog(@"granted claendar access");
dispatch_async(dispatch_get_main_queue(), ^{
if (error)
{
calChk = 0;
}
else if (!granted)
{
calChk = 0;
}
else
{
calChk = 1;
}
});
}];
}
else
{
calChk = 1;
}
if(calChk == 1) // This gets executed before completion block completes and as //a result the callChk value is 0
{
return [self saveTaskToCalendar:eventStore];
}
else
{
return @"";
}
}
- (NSString *) saveTaskToCalendar: (EKEventStore *) eventStore
{
EKEvent *event = [EKEvent eventWithEventStore:eventStore];
event.title = @"EXEXEX";
event.startDate = [standardFM dateFromString:dateString];
NSDateComponents *dateComps = [[NSDateComponents alloc] init];
dateComps.minute = 5;
event.endDate = [[NSCalendar currentCalendar] dateByAddingComponents:dateComps toDate:event.startDate options:0];
EKAlarm *eventAlarm = [EKAlarm alarmWithAbsoluteDate:event.startDate];
event.alarms = [NSArray arrayWithObject:eventAlarm];
event.notes = @"dwqdqd";
[event setCalendar:[eventStore defaultCalendarForNewEvents]];
NSError *err;
[eventStore saveEvent:event span:EKSpanThisEvent error:&err];
if(! [[err description] isEqualToString:@"(null)"])
{
NSLog(@"Event ID: %@", event.eventIdentifier);
return event.eventIdentifier;
}
else
{
NSLog(@"Calendar error: %@", err);
return @"";
}
}