所以我从iOS日历中检索事件(在某个谓词中),将它们排序并存储在一个数组中;然后我获取第一个事件的标题,时间和位置,并在故事板上将它们显示为UILabels。 我遇到的第一个问题是,当我构建并运行应用程序时,不会显示任何内容。我必须退出应用程序(从多任务处理)并从模拟器运行它,并在每次延迟10秒后显示(我的第二个问题)。 我正在我的视图控制器的(void)viewDidLoad函数中运行以上所有代码,我认为问题来自于此。有没有办法在应用程序启动之前或启动时运行代码,这样用户就不必等待他的事件加载? 谢谢! 这是我的代码:
//Load Calendar Events
EKEventStore *store = [[EKEventStore alloc] init];
[store requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted,
NSError *error) {
if (granted) {
NSLog(@"User has granted permission");
// Get the appropriate calendar
NSCalendar *calendar = [NSCalendar currentCalendar];
//Create the start date component
NSDateComponents *nowComponents = [[NSDateComponents alloc] init];
nowComponents.hour = 0;
NSDate *now = [calendar dateByAddingComponents:nowComponents
toDate:[NSDate date]
options:0];
// Create the end date components
NSDateComponents *oneDayFromNowComponents = [[NSDateComponents alloc] init];
oneDayFromNowComponents.day = 1;
NSDate *todayEnd = [calendar dateByAddingComponents:oneDayFromNowComponents
toDate:[NSDate date]
options:0];
// Create the predicate from the event store's instance method
NSPredicate *predicate = [store predicateForEventsWithStartDate:now
endDate:todayEnd
calendars:nil];
// Fetch all events that match the predicate
NSArray *events = [store eventsMatchingPredicate:predicate];
NSLog(@"The events in the array are %@", events);
NSArray *sortedArray = [events sortedArrayUsingComparator:^NSComparisonResult(EKEvent *event1, EKEvent *event2) {
return [event1.startDate compare:event2.startDate];
}];
//Sort events according to date and fetch the one at index 0
if ([sortedArray count] == 0){
NSString *noEvent = (@"No Upcoming Events");
NSString *noDescription = (@"No scheduled events for the day.");
NSString *noLocale = (@"");
self.eventTime.text = noEvent;
self.eventTitle.text = noDescription;
self.eventLocation.text = noLocale;
} else {
EKEvent *event = [sortedArray objectAtIndex:0];
self.eventTitle.text = event.title;
self.eventLocation.text = event.location;
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = @"hh:mma";
self.eventTime.text = [NSString stringWithFormat:@"%@ - %@", [formatter stringFromDate:event.startDate], [formatter stringFromDate:event.endDate]];
}
} else {
NSLog(@"User has not granted permission");
}
}];