So I'm retrieving events from the iOS Calendar (within a certain predicate), sorting and storing them in an array; then I fetch the first event's title, time and location and display them as UILabels on Storyboard. The first problem I encounter is that when I build and run the application, nothing is displayed. I have to quit the app (from multitasking) and just run it from the simulator and it shows up, after a delay of 10 seconds every time (my second problem). I'm running all the above code in the (void)viewDidLoad function of my view controller which where I think the problem is from. Is there any way of running the code before or while the app is launching so the user doesn't have to wait for his events to load? Thanks! Here's my code:
//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");
}
}];