Monday, 18 July 2016

How to create, delete, edit, fetch events from the Calendar using EventKit framework in iOS

Today we will learn how to get access to iOS calendar and then access the events of it. You can read more about EventKit framework here.

Now we will write code for that.

Steps
 1. Create a new Xcode Project (Lets say CalendarDemo).
 2.  Now go to StoryBoard and design your Layout Like this.
3. Basically You have to take 5 buttons and a Label.
4. Make Proper connection for the Buttons.



5. Now import this in your ViewController.m  #import <EventKit/EventKit.h>

6.Now define Action For the Buttons

#import "ViewController.h"
#import <EventKit/EventKit.h>

@interface ViewController ()
@property(strong,nonatomic) NSMutableArray *eventDetailsArray;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.eventDetailsArray = [[NSMutableArray alloc]init];
    // Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



- (IBAction)getCalenderAccess:(id)sender {
    EKEventStore *eventStore = [[EKEventStore alloc]init];
    if([eventStore respondsToSelector:@selector(requestAccessToEntityType:completion:)]) {
        [eventStore requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted,NSError* error){
            
            //Access not granted-------------
            if(!granted){
                NSString *message = @"Hey! I Can't access your Calendar... check your privacy settings to let me in!";
                UIAlertController *controller = [UIAlertController alertControllerWithTitle:@"Alert" message:message preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *defaultaction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:nil];
                [controller addAction:defaultaction ];
                [self presentViewController:controller animated:YES completion:nil];
                dispatch_async(dispatch_get_main_queue(), ^{
                    
                }
                               );
                
                //Access granted------------------
            }else{
                
                NSString *message = @"Hey! Thanks For that!";
                UIAlertController *controller = [UIAlertController alertControllerWithTitle:@"Alert" message:message preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *defaultaction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:nil];
                [controller addAction:defaultaction ];
                [self presentViewController:controller animated:YES completion:nil];            }
        }];
    }
    
    //Device prior to iOS 6.0  *********************************************
    else{
        
        
    }
    
    
}

- (IBAction)createEventButtonAction:(id)sender {
    
    EKEventStore *store = [EKEventStore new];
    [store requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError *error) {
        if (!granted) { return; }
        EKEvent *event = [EKEvent eventWithEventStore:store];
        event.title = @"iostpoint.wordpress.com";
        event.startDate = [NSDate date]; //today
        event.endDate = [event.startDate dateByAddingTimeInterval:60*60];  //set 1 hour delay
        event.calendar = [store defaultCalendarForNewEvents];
        NSError *err = nil;
        [store saveEvent:event span:EKSpanThisEvent commit:YES error:&err];
        
    }];
}
- (IBAction)deleteEventButtonAction:(id)sender {
    
    EKEventStore *store = [EKEventStore new];
    [store requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError *error) {
        if (!granted) { return; }
        NSPredicate *fetchCalendarEvents = [store predicateForEventsWithStartDate:[NSDate date] endDate:[[NSDate date] dateByAddingTimeInterval:60*60] calendars:nil];
        self.eventDetailsArray = [NSMutableArray arrayWithArray:[store eventsMatchingPredicate:fetchCalendarEvents]];
        EKEvent *currentEvent = [self.eventDetailsArray objectAtIndex:0];
        EKEvent *event = [store eventWithIdentifier:currentEvent.eventIdentifier];
        event.calendar = [store defaultCalendarForNewEvents];
        [store removeEvent:event span:EKSpanThisEvent error:nil];
    }];

    
}
- (IBAction)editEventButtonAction:(id)sender {
    
    EKEventStore *store = [EKEventStore new];
    [store requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError *error) {
        if (!granted) { return; }
        NSPredicate *fetchCalendarEvents = [store predicateForEventsWithStartDate:[NSDate date] endDate:[[NSDate date] dateByAddingTimeInterval:60*60] calendars:nil];
        self.eventDetailsArray = [NSMutableArray arrayWithArray:[store eventsMatchingPredicate:fetchCalendarEvents]];
        EKEvent *currentEvent = [self.eventDetailsArray objectAtIndex:0];
        EKEvent *event = [store eventWithIdentifier:currentEvent.eventIdentifier];
        event.title = @"iostpoint.blogspot.com";
        event.calendar = [store defaultCalendarForNewEvents];
        NSError *err = nil;
        [store saveEvent:event span:EKSpanThisEvent commit:YES error:&err];
        //save the event id if you want to access this later
    }];
    
}

- (IBAction)fetchAllEventButtonAction:(id)sender {
     EKEventStore *store = [[EKEventStore alloc]init];
    NSPredicate *fetchCalendarEvents = [store predicateForEventsWithStartDate:[NSDate date] endDate:[[NSDate date] dateByAddingTimeInterval:60*60] calendars:nil];
    self.eventDetailsArray = [NSMutableArray arrayWithArray:[store eventsMatchingPredicate:fetchCalendarEvents]];
       for (int i =0; i< [self.eventDetailsArray count]; i++) {
            EKEvent *event = [self.eventDetailsArray objectAtIndex:i];
           NSLog(@"Event Title %@",event.title);
            }

}

7. Now run the code.
a. First Click the GetAccess Button.
b. Then Click on the Create Event button, it will create new event in your Calendar.

c. Click on edit button. It will change the title of your first event. You can change it according to Your need.

 d. Now click on delete Button, it will delete the first event. Change it according to your need.
If you like this post. Then do share and give your useful feedback.
You can download the whole source code from here.

Enjoy Coding :)

No comments:

Post a Comment

Ads Inside Post

Blogger Widget