-
Notifications
You must be signed in to change notification settings - Fork 401
/
Copy pathCalendar.m
952 lines (790 loc) · 41.5 KB
/
Calendar.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
#import "Calendar.h"
#import <Cordova/CDV.h>
#import <EventKitUI/EventKitUI.h>
#import <EventKit/EventKit.h>
#define SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending)
@implementation Calendar
@synthesize eventStore;
@synthesize interactiveCallbackId;
#pragma mark Initialization functions
- (void) pluginInitialize {
[self initEventStoreWithCalendarCapabilities];
}
- (void) initEventStoreWithCalendarCapabilities {
__block BOOL accessGranted = NO;
EKEventStore* eventStoreCandidate = [[EKEventStore alloc] init];
if([eventStoreCandidate respondsToSelector:@selector(requestAccessToEntityType:completion:)]) {
dispatch_semaphore_t sema = dispatch_semaphore_create(0);
[eventStoreCandidate requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError *error) {
accessGranted = granted;
dispatch_semaphore_signal(sema);
}];
dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
} else { // we're on iOS 5 or older
accessGranted = YES;
}
if (accessGranted) {
self.eventStore = eventStoreCandidate;
}
}
#pragma mark Helper Functions
- (void) createEventWithCalendar:(CDVInvokedUrlCommand*)command
calendar: (EKCalendar *) calendar {
NSDictionary* options = [command.arguments objectAtIndex:0];
NSString* title = [options objectForKey:@"title"];
NSString* location = [options objectForKey:@"location"];
NSString* notes = [options objectForKey:@"notes"];
NSNumber* startTime = [options objectForKey:@"startTime"];
NSNumber* endTime = [options objectForKey:@"endTime"];
[self.commandDelegate runInBackground: ^{
NSTimeInterval _startInterval = [startTime doubleValue] / 1000; // strip millis
NSDate *myStartDate = [NSDate dateWithTimeIntervalSince1970:_startInterval];
NSTimeInterval _endInterval = [endTime doubleValue] / 1000; // strip millis
EKEvent *myEvent = [EKEvent eventWithEventStore: self.eventStore];
myEvent.title = title;
myEvent.location = location;
myEvent.notes = notes;
myEvent.startDate = myStartDate;
int duration = _endInterval - _startInterval;
int moduloDay = duration % (60 * 60 * 24);
if (moduloDay == 0) {
myEvent.allDay = YES;
myEvent.endDate = [NSDate dateWithTimeIntervalSince1970:_endInterval - 1];
} else {
myEvent.endDate = [NSDate dateWithTimeIntervalSince1970:_endInterval];
}
myEvent.calendar = calendar;
// if a custom reminder is required: use createCalendarWithOptions
EKAlarm *reminder = [EKAlarm alarmWithRelativeOffset:-1 * 60 * 60];
[myEvent addAlarm:reminder];
NSError *error = nil;
[self.eventStore saveEvent:myEvent span:EKSpanThisEvent error:&error];
CDVPluginResult *pluginResult = nil;
if (error) {
pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:error.userInfo.description];
} else {
NSLog(@"Reached Success");
pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];
}
[self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}];
}
- (EKRecurrenceFrequency) toEKRecurrenceFrequency:(NSString*) recurrence {
if ([recurrence isEqualToString:@"daily"]) {
return EKRecurrenceFrequencyDaily;
} else if ([recurrence isEqualToString:@"weekly"]) {
return EKRecurrenceFrequencyWeekly;
} else if ([recurrence isEqualToString:@"monthly"]) {
return EKRecurrenceFrequencyMonthly;
} else if ([recurrence isEqualToString:@"yearly"]) {
return EKRecurrenceFrequencyYearly;
}
// default to daily, so invoke this method only when recurrence is set
return EKRecurrenceFrequencyDaily;
}
- (void) modifyEventWithOptions:(CDVInvokedUrlCommand*)command {
NSDictionary* options = [command.arguments objectAtIndex:0];
NSString* title = [options objectForKey:@"title"];
NSString* location = [options objectForKey:@"location"];
NSString* notes = [options objectForKey:@"notes"];
NSNumber* startTime = [options objectForKey:@"startTime"];
NSNumber* endTime = [options objectForKey:@"endTime"];
NSString* ntitle = [options objectForKey:@"newTitle"];
NSString* nlocation = [options objectForKey:@"newLocation"];
NSString* nnotes = [options objectForKey:@"newNotes"];
NSNumber* nstartTime = [options objectForKey:@"newStartTime"];
NSNumber* nendTime = [options objectForKey:@"newEndTime"];
NSTimeInterval _startInterval = [startTime doubleValue] / 1000; // strip millis
NSDate *myStartDate = [NSDate dateWithTimeIntervalSince1970:_startInterval];
NSTimeInterval _endInterval = [endTime doubleValue] / 1000; // strip millis
NSDate *myEndDate = [NSDate dateWithTimeIntervalSince1970:_endInterval];
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSDictionary* calOptions = [options objectForKey:@"options"];
NSString* calEventID = [calOptions objectForKey:@"id"];
// the only search param we're currently matching against is the calendarName, so ignoring any passed reminder values etc
NSString* calendarName = [calOptions objectForKey:@"calendarName"];
[self.commandDelegate runInBackground: ^{
NSArray *calendars = nil;
if (calendarName == (id)[NSNull null]) {
calendars = [self.eventStore calendarsForEntityType:EKEntityTypeEvent];
if (calendars.count == 0) {
CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"No default calendar found. Is access to the Calendar blocked for this app?"];
[self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
return;
}
} else {
EKCalendar * calendar = [self findEKCalendar:calendarName];
if (calendar == nil) {
CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Could not find calendar"];
[self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
return;
} else {
calendars = [NSArray arrayWithObject:calendar];
}
}
EKEvent *theEvent = nil;
// Find matches
if (calEventID != nil) {
theEvent = [self.eventStore calendarItemWithIdentifier:calEventID];
}
if (theEvent == nil) {
NSArray *matchingEvents = [self findEKEventsWithTitle:title location:location notes:notes startDate:myStartDate endDate:myEndDate calendars:calendars];
if (matchingEvents.count == 1) {
// Presume we have to have an exact match to modify it!
// Need to load this event from an EKEventStore so we can edit it
theEvent = [self.eventStore eventWithIdentifier:((EKEvent*)[matchingEvents lastObject]).eventIdentifier];
}
}
CDVPluginResult *pluginResult = nil;
if (theEvent != nil) {
NSDictionary* newCalOptions = [options objectForKey:@"newOptions"];
NSString* newCalendarName = [newCalOptions objectForKey:@"calendarName"];
if (newCalendarName != (id)[NSNull null]) {
theEvent.calendar = [self findEKCalendar:calendarName];
if (theEvent.calendar == nil) {
pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Could not find calendar passed in newOptions object"];
[self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
return;
}
}
if (ntitle) {
theEvent.title = ntitle;
}
if (nlocation) {
theEvent.location = nlocation;
}
if (nnotes) {
theEvent.notes = nnotes;
}
if (nstartTime) {
NSTimeInterval _nstartInterval = [nstartTime doubleValue] / 1000; // strip millis
theEvent.startDate = [NSDate dateWithTimeIntervalSince1970:_nstartInterval];
}
if (nendTime) {
NSTimeInterval _nendInterval = [nendTime doubleValue] / 1000; // strip millis
theEvent.endDate = [NSDate dateWithTimeIntervalSince1970:_nendInterval];
}
// remove any existing alarms because there would be no other way to remove them
for (EKAlarm *alarm in theEvent.alarms) {
[theEvent removeAlarm:alarm];
}
NSNumber* firstReminderMinutes = [newCalOptions objectForKey:@"firstReminderMinutes"];
if (firstReminderMinutes != (id)[NSNull null]) {
EKAlarm *reminder = [EKAlarm alarmWithRelativeOffset:-1*firstReminderMinutes.intValue*60];
[theEvent addAlarm:reminder];
}
NSNumber* secondReminderMinutes = [newCalOptions objectForKey:@"secondReminderMinutes"];
if (secondReminderMinutes != (id)[NSNull null]) {
EKAlarm *reminder = [EKAlarm alarmWithRelativeOffset:-1*secondReminderMinutes.intValue*60];
[theEvent addAlarm:reminder];
}
NSString* recurrence = [newCalOptions objectForKey:@"recurrence"];
NSNumber* intervalAmount = [newCalOptions objectForKey:@"recurrenceInterval"];
if (recurrence != (id)[NSNull null]) {
EKRecurrenceRule *rule = [[EKRecurrenceRule alloc] initRecurrenceWithFrequency: [self toEKRecurrenceFrequency:recurrence]
interval: intervalAmount.integerValue
end: nil];
NSString* recurrenceEndTime = [newCalOptions objectForKey:@"recurrenceEndTime"];
if (recurrenceEndTime != nil) {
NSTimeInterval _recurrenceEndTimeInterval = [recurrenceEndTime doubleValue] / 1000; // strip millis
NSDate *myRecurrenceEndDate = [NSDate dateWithTimeIntervalSince1970:_recurrenceEndTimeInterval];
EKRecurrenceEnd *end = [EKRecurrenceEnd recurrenceEndWithEndDate:myRecurrenceEndDate];
rule.recurrenceEnd = end;
}
[theEvent addRecurrenceRule:rule];
}
NSString* url = [newCalOptions objectForKey:@"url"];
if (url != (id)[NSNull null]) {
NSURL* myUrl = [NSURL URLWithString:url];
theEvent.URL = myUrl;
}
// Now save the new details back to the store
NSError *error = nil;
[self.eventStore saveEvent:theEvent span:EKSpanThisEvent error:&error];
// Check error code + return result
if (error) {
pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:error.userInfo.description];
} else {
pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:theEvent.calendarItemIdentifier];
}
} else {
// Otherwise return a no result error (could be more than 1, but not a biggie)
pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_NO_RESULT];
}
[self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}];
}
- (void) deleteEventFromCalendar:(CDVInvokedUrlCommand*)command
calendar: (EKCalendar *) calendar {
NSDictionary* options = [command.arguments objectAtIndex:0];
NSString* title = [options objectForKey:@"title"];
NSString* location = [options objectForKey:@"location"];
NSString* notes = [options objectForKey:@"notes"];
NSNumber* startTime = [options objectForKey:@"startTime"];
NSNumber* endTime = [options objectForKey:@"endTime"];
[self.commandDelegate runInBackground: ^{
NSTimeInterval _startInterval = [startTime doubleValue] / 1000; // strip millis
NSDate *myStartDate = [NSDate dateWithTimeIntervalSince1970:_startInterval];
NSTimeInterval _endInterval = [endTime doubleValue] / 1000; // strip millis
NSDate *myEndDate = [NSDate dateWithTimeIntervalSince1970:_endInterval];
NSArray *calendars = [NSArray arrayWithObject:calendar];
NSArray *matchingEvents = [self findEKEventsWithTitle:title location:location notes:notes startDate:myStartDate endDate:myEndDate calendars:calendars];
NSError *error = NULL;
for (EKEvent * event in matchingEvents) {
// NOTE: as per issue #150 you can delete this event AND future events by passing span:EKSpanFutureEvents
[self.eventStore removeEvent:event span:EKSpanThisEvent error:&error];
}
CDVPluginResult *pluginResult = nil;
if (error) {
pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:error.userInfo.description];
} else {
pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:[@"Deleted from " stringByAppendingString:calendar.title]];
}
[self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}];
}
- (NSArray*) findEKEventsWithTitle: (NSString *)title
location: (NSString *)location
notes: (NSString *)notes
startDate: (NSDate *)startDate
endDate: (NSDate *)endDate
calendars: (NSArray*)calendars {
NSMutableArray *predicateStrings = [NSMutableArray arrayWithCapacity:3];
if (title != (id)[NSNull null] && title.length > 0) {
title = [title stringByReplacingOccurrencesOfString:@"'" withString:@"\\'"];
[predicateStrings addObject:[NSString stringWithFormat:@"title contains[c] '%@'", title]];
}
if (location != (id)[NSNull null] && location.length > 0) {
location = [location stringByReplacingOccurrencesOfString:@"'" withString:@"\\'"];
[predicateStrings addObject:[NSString stringWithFormat:@"location contains[c] '%@'", location]];
}
if (notes != (id)[NSNull null] && notes.length > 0) {
notes = [notes stringByReplacingOccurrencesOfString:@"'" withString:@"\\'"];
[predicateStrings addObject:[NSString stringWithFormat:@"notes contains[c] '%@'", notes]];
}
NSString *predicateString = [predicateStrings componentsJoinedByString:@" AND "];
NSPredicate *matches;
NSArray *datedEvents, *matchingEvents;
if (predicateString.length > 0) {
matches = [NSPredicate predicateWithFormat:predicateString];
datedEvents = [self.eventStore eventsMatchingPredicate:[eventStore predicateForEventsWithStartDate:startDate endDate:endDate calendars:calendars]];
matchingEvents = [datedEvents filteredArrayUsingPredicate:matches];
} else {
datedEvents = [self.eventStore eventsMatchingPredicate:[eventStore predicateForEventsWithStartDate:startDate endDate:endDate calendars:calendars]];
matchingEvents = datedEvents;
}
return matchingEvents;
}
- (EKCalendar*) findEKCalendar: (NSString *)calendarName {
for (EKCalendar *thisCalendar in [self.eventStore calendarsForEntityType:EKEntityTypeEvent]){
NSLog(@"Calendar: %@", thisCalendar.title);
if ([thisCalendar.title isEqualToString:calendarName]) {
return thisCalendar;
}
}
NSLog(@"No match found for calendar with name: %@", calendarName);
return nil;
}
- (EKSource*) findEKSource {
// if iCloud is on, it hides the local calendars, so check for iCloud first
for (EKSource *source in self.eventStore.sources) {
if (source.sourceType == EKSourceTypeCalDAV && [source.title isEqualToString:@"iCloud"]) {
return source;
}
}
// ok, not found.. so it's a local calendar
for (EKSource *source in self.eventStore.sources) {
if (source.sourceType == EKSourceTypeLocal) {
return source;
}
}
return nil;
}
- (NSMutableArray*) eventsToDataArray: (NSArray*)matchingEvents {
NSMutableArray *results = [[NSMutableArray alloc] initWithCapacity:matchingEvents.count];
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
for (EKEvent * event in matchingEvents) {
NSMutableDictionary *entry = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
event.title, @"title",
event.calendar.title, @"calendar",
[df stringFromDate:event.startDate], @"startDate",
[df stringFromDate:event.endDate], @"endDate",
nil];
// optional fields
if (event.location != nil) {
[entry setObject:event.location forKey:@"location"];
}
if (event.notes != nil) {
[entry setObject:event.notes forKey:@"message"];
}
if (event.attendees != nil) {
NSMutableArray * attendees = [[NSMutableArray alloc] init];
for (EKParticipant * participant in event.attendees) {
NSString *role = [[NSArray arrayWithObjects:@"Unknown", @"Required", @"Optional", @"Chair", @"Non Participant", nil] objectAtIndex:participant.participantRole];
NSString *status = [[NSArray arrayWithObjects:@"Unknown", @"Pending", @"Accepted", @"Declined", @"Tentative", @"Delegated", @"Completed", @"In Process", nil] objectAtIndex:participant.participantStatus];
NSString *type = [[NSArray arrayWithObjects:@"Unknown", @"Person", @"Room", @"Resource", @"Group", nil] objectAtIndex:participant.participantType];
NSMutableDictionary *attendeeEntry = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
participant.name, @"name",
[participant.URL absoluteString], @"URL",
status, @"status",
type, @"type",
role, @"role",
nil];
[attendees addObject:attendeeEntry];
}
[entry setObject:attendees forKey:@"attendees"];
}
[entry setObject:event.calendarItemIdentifier forKey:@"id"];
[results addObject:entry];
}
return results;
}
#pragma mark Cordova functions
- (void) openCalendar:(CDVInvokedUrlCommand*)command {
NSDictionary* options = [command.arguments objectAtIndex:0];
NSNumber* date = [options objectForKey:@"date"];
[self.commandDelegate runInBackground: ^{
NSTimeInterval _startInterval = [date doubleValue] / 1000; // strip millis
NSDate *openDate = [NSDate dateWithTimeIntervalSince1970:_startInterval];
NSInteger interval = [openDate timeIntervalSinceReferenceDate];
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"calshow:%ld", interval]];
[[UIApplication sharedApplication] openURL:url];
}];
}
- (void) listCalendars:(CDVInvokedUrlCommand*)command {
[self.commandDelegate runInBackground: ^{
NSArray * calendars = [self.eventStore calendarsForEntityType:EKEntityTypeEvent];
NSMutableArray *finalResults = [[NSMutableArray alloc] initWithCapacity:calendars.count];
for (EKCalendar *thisCalendar in calendars) {
NSString *type = [[NSArray arrayWithObjects:@"Local", @"CalDAV", @"Exchange", @"Subscription", @"Birthday", @"Mail", nil] objectAtIndex:thisCalendar.type];
NSMutableDictionary *entry = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
thisCalendar.calendarIdentifier, @"id",
thisCalendar.title, @"name",
type, @"type",
nil];
[finalResults addObject:entry];
}
CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus: CDVCommandStatus_OK messageAsArray:finalResults];
[self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}];
}
- (void) listEventsInRange:(CDVInvokedUrlCommand*)command {
}
- (void)createEventWithOptions:(CDVInvokedUrlCommand*)command {
NSDictionary* options = [command.arguments objectAtIndex:0];
NSString* title = [options objectForKey:@"title"];
NSString* location = [options objectForKey:@"location"];
NSString* notes = [options objectForKey:@"notes"];
NSNumber* startTime = [options objectForKey:@"startTime"];
NSNumber* endTime = [options objectForKey:@"endTime"];
NSDictionary* calOptions = [options objectForKey:@"options"];
NSNumber* firstReminderMinutes = [calOptions objectForKey:@"firstReminderMinutes"];
NSNumber* secondReminderMinutes = [calOptions objectForKey:@"secondReminderMinutes"];
NSString* recurrence = [calOptions objectForKey:@"recurrence"];
NSString* recurrenceEndTime = [calOptions objectForKey:@"recurrenceEndTime"];
NSNumber* recurrenceIntervalAmount = [calOptions objectForKey:@"recurrenceInterval"];
NSString* calendarName = [calOptions objectForKey:@"calendarName"];
NSString* url = [calOptions objectForKey:@"url"];
NSDictionary* attendeesList = [calOptions objectForKey:@"attendees"];
[self.commandDelegate runInBackground: ^{
EKEvent *myEvent = [EKEvent eventWithEventStore: self.eventStore];
if (url != (id)[NSNull null]) {
NSURL* myUrl = [NSURL URLWithString:url];
myEvent.URL = myUrl;
}
NSTimeInterval _startInterval = [startTime doubleValue] / 1000; // strip millis
NSDate *myStartDate = [NSDate dateWithTimeIntervalSince1970:_startInterval];
NSTimeInterval _endInterval = [endTime doubleValue] / 1000; // strip millis
myEvent.title = title;
myEvent.location = location;
myEvent.notes = notes;
myEvent.startDate = myStartDate;
int duration = _endInterval - _startInterval;
int moduloDay = duration % (60*60*24);
if (moduloDay == 0) {
myEvent.allDay = YES;
myEvent.endDate = [NSDate dateWithTimeIntervalSince1970:_endInterval-1];
} else {
myEvent.endDate = [NSDate dateWithTimeIntervalSince1970:_endInterval];
}
EKCalendar* calendar = nil;
CDVPluginResult *pluginResult = nil;
if (calendarName == (id)[NSNull null]) {
calendar = self.eventStore.defaultCalendarForNewEvents;
if (calendar == nil) {
pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"No default calendar found. Is access to the Calendar blocked for this app?"];
[self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
return;
}
} else {
calendar = [self findEKCalendar:calendarName];
if (calendar == nil) {
// create it
calendar = [EKCalendar calendarForEntityType:EKEntityTypeEvent eventStore:self.eventStore];
calendar.title = calendarName;
calendar.source = [self findEKSource];
NSError* error;
[self.eventStore saveCalendar:calendar commit:YES error:&error];
if (error != nil) {
NSLog(@"could not create calendar, error: %@", error.description);
pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Calendar could not be found nor created. Is access to the Calendar blocked for this app?"];
[self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
return;
}
}
}
myEvent.calendar = calendar;
if (firstReminderMinutes != (id)[NSNull null]) {
EKAlarm *reminder = [EKAlarm alarmWithRelativeOffset:-1*firstReminderMinutes.intValue*60];
[myEvent addAlarm:reminder];
}
if (secondReminderMinutes != (id)[NSNull null]) {
EKAlarm *reminder = [EKAlarm alarmWithRelativeOffset:-1*secondReminderMinutes.intValue*60];
[myEvent addAlarm:reminder];
}
if (recurrence != (id)[NSNull null]) {
EKRecurrenceRule *rule = [[EKRecurrenceRule alloc] initRecurrenceWithFrequency: [self toEKRecurrenceFrequency:recurrence]
interval: recurrenceIntervalAmount.integerValue
end: nil];
if (recurrenceEndTime != nil) {
NSTimeInterval _recurrenceEndTimeInterval = [recurrenceEndTime doubleValue] / 1000; // strip millis
NSDate *myRecurrenceEndDate = [NSDate dateWithTimeIntervalSince1970:_recurrenceEndTimeInterval];
EKRecurrenceEnd *end = [EKRecurrenceEnd recurrenceEndWithEndDate:myRecurrenceEndDate];
rule.recurrenceEnd = end;
}
[myEvent addRecurrenceRule:rule];
}
if (attendeesList != (id)[NSNull null]) {
NSMutableArray *attendees = [NSMutableArray new];
for(id attendee in attendeesList){
//Initialize a EKAttendee object, which is not accessible and inherits from EKParticipant
Class className = NSClassFromString(@"EKAttendee");
id attendeeObject = [className new];
//Set the properties of this attendee using setValue:forKey:
[attendeeObject setValue:[[attendeesList objectForKey:attendee] objectForKey:@"firstName"] forKey:@"firstName"];
[attendeeObject setValue:[[attendeesList objectForKey:attendee] objectForKey:@"lastName"] forKey:@"lastName"];
[attendeeObject setValue:[[attendeesList objectForKey:attendee] objectForKey:@"emailAddress"] forKey:@"emailAddress"];
[attendees addObject:attendeeObject];
}
//Finally, add the invitees to the event
[myEvent setValue:attendees forKey:@"attendees"];
}
NSError *error = nil;
[self.eventStore saveEvent:myEvent span:EKSpanThisEvent error:&error];
if (error) {
pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:error.userInfo.description];
} else {
pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:myEvent.calendarItemIdentifier];
}
[self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}];
}
- (void) createEventInteractively:(CDVInvokedUrlCommand*)command {
NSDictionary* options = [command.arguments objectAtIndex:0];
NSString* title = [options objectForKey:@"title"];
NSString* location = [options objectForKey:@"location"];
NSString* notes = [options objectForKey:@"notes"];
NSNumber* startTime = [options objectForKey:@"startTime"];
NSNumber* endTime = [options objectForKey:@"endTime"];
NSDictionary* calOptions = [options objectForKey:@"options"];
NSNumber* firstReminderMinutes = [calOptions objectForKey:@"firstReminderMinutes"];
NSNumber* secondReminderMinutes = [calOptions objectForKey:@"secondReminderMinutes"];
NSString* recurrence = [calOptions objectForKey:@"recurrence"];
NSString* recurrenceEndTime = [calOptions objectForKey:@"recurrenceEndTime"];
NSString* calendarName = [calOptions objectForKey:@"calendarName"];
NSString* url = [calOptions objectForKey:@"url"];
NSNumber* intervalAmount = [calOptions objectForKey:@"recurrenceInterval"];
EKEvent *myEvent = [EKEvent eventWithEventStore: self.eventStore];
if (url != (id)[NSNull null]) {
NSURL* myUrl = [NSURL URLWithString:url];
myEvent.URL = myUrl;
}
if (startTime != (id)[NSNull null]) {
NSTimeInterval _startInterval = [startTime doubleValue] / 1000; // strip millis
NSDate *myStartDate = [NSDate dateWithTimeIntervalSince1970:_startInterval];
myEvent.startDate = myStartDate;
}
if (endTime != (id)[NSNull null]) {
NSTimeInterval _endInterval = [endTime doubleValue] / 1000; // strip millis
if (startTime != (id)[NSNull null]) {
NSTimeInterval _startInterval = [startTime doubleValue] / 1000; // strip millis
int duration = _endInterval - _startInterval;
int moduloDay = duration % (60 * 60 * 24);
if (moduloDay == 0) {
myEvent.allDay = YES;
myEvent.endDate = [NSDate dateWithTimeIntervalSince1970:_endInterval - 1];
} else {
myEvent.endDate = [NSDate dateWithTimeIntervalSince1970:_endInterval];
}
} else {
myEvent.endDate = [NSDate dateWithTimeIntervalSince1970:_endInterval];
}
}
myEvent.title = title;
myEvent.location = location;
myEvent.notes = notes;
[self.commandDelegate runInBackground: ^{
EKCalendar* calendar = nil;
if (calendarName == (id)[NSNull null]) {
calendar = self.eventStore.defaultCalendarForNewEvents;
if (calendar == nil) {
CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"No default calendar found. Is access to the Calendar blocked for this app?"];
[self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
return;
}
} else {
calendar = [self findEKCalendar:calendarName];
if (calendar == nil) {
CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Could not find calendar"];
[self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
return;
}
}
myEvent.calendar = calendar;
if (firstReminderMinutes != (id)[NSNull null]) {
EKAlarm *reminder = [EKAlarm alarmWithRelativeOffset:-1 * firstReminderMinutes.intValue * 60];
[myEvent addAlarm:reminder];
}
if (secondReminderMinutes != (id)[NSNull null]) {
EKAlarm *reminder = [EKAlarm alarmWithRelativeOffset:-1 * secondReminderMinutes.intValue * 60];
[myEvent addAlarm:reminder];
}
if (recurrence != (id)[NSNull null]) {
[self.commandDelegate runInBackground: ^{
EKRecurrenceRule *rule = [[EKRecurrenceRule alloc] initRecurrenceWithFrequency: [self toEKRecurrenceFrequency:recurrence]
interval: intervalAmount.integerValue
end: nil];
if (recurrenceEndTime != nil) {
NSTimeInterval _recurrenceEndTimeInterval = [recurrenceEndTime doubleValue] / 1000; // strip millis
NSDate *myRecurrenceEndDate = [NSDate dateWithTimeIntervalSince1970:_recurrenceEndTimeInterval];
EKRecurrenceEnd *end = [EKRecurrenceEnd recurrenceEndWithEndDate:myRecurrenceEndDate];
rule.recurrenceEnd = end;
}
[myEvent addRecurrenceRule:rule];
}];
}
self.interactiveCallbackId = command.callbackId;
EKEventEditViewController* controller = [[EKEventEditViewController alloc] init];
controller.event = myEvent;
controller.eventStore = self.eventStore;
controller.editViewDelegate = self;
[self.viewController presentViewController:controller animated:YES completion:nil];
}];
}
- (void) deleteEventFromNamedCalendar:(CDVInvokedUrlCommand*)command {
NSDictionary* options = [command.arguments objectAtIndex:0];
NSString* calendarName = [options objectForKey:@"calendarName"];
EKCalendar* calendar = [self findEKCalendar:calendarName];
if (calendar == nil) {
CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Could not find calendar"];
[self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
} else {
[self deleteEventFromCalendar:command calendar:calendar];
NSString *msg = [@"Deleted from " stringByAppendingString:calendar.title];
CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:msg];
[self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}
}
- (void) deleteEvent:(CDVInvokedUrlCommand*)command {
EKCalendar* calendar = self.eventStore.defaultCalendarForNewEvents;
if (calendar == nil) {
CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"No default calendar found. Is access to the Calendar blocked for this app?"];
[self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
} else {
[self deleteEventFromCalendar:command calendar: calendar];
}
}
- (void) findAllEventsInNamedCalendar:(CDVInvokedUrlCommand*)command {
NSDictionary* options = [command.arguments objectAtIndex:0];
NSString* calendarName = [options objectForKey:@"calendarName"];
EKCalendar* calendar = [self findEKCalendar:calendarName];
CDVPluginResult *pluginResult = nil;
if (calendar == nil) {
pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Could not find calendar"];
} else {
NSDate* endDate = [NSDate dateWithTimeIntervalSinceNow:[[NSDate distantFuture] timeIntervalSinceReferenceDate]];
NSArray *calendarArray = [NSArray arrayWithObject:calendar];
NSPredicate *fetchCalendarEvents = [eventStore predicateForEventsWithStartDate:[NSDate date] endDate:endDate calendars:calendarArray];
NSArray *matchingEvents = [eventStore eventsMatchingPredicate:fetchCalendarEvents];
NSMutableArray * eventsDataArray = [self eventsToDataArray:matchingEvents];
pluginResult = [CDVPluginResult resultWithStatus: CDVCommandStatus_OK messageAsArray:eventsDataArray];
}
[self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}
- (void) findEventWithOptions:(CDVInvokedUrlCommand*)command {
NSDictionary* options = [command.arguments objectAtIndex:0];
NSString* title = [options objectForKey:@"title"];
NSString* location = [options objectForKey:@"location"];
NSString* notes = [options objectForKey:@"notes"];
NSNumber* startTime = [options objectForKey:@"startTime"];
NSNumber* endTime = [options objectForKey:@"endTime"];
// actually the only option we're currently using is calendarName
NSDictionary* calOptions = [options objectForKey:@"options"];
NSString* calEventID = [calOptions objectForKey:@"id"];
NSString* calendarName = [calOptions objectForKey:@"calendarName"];
[self.commandDelegate runInBackground: ^{
NSTimeInterval _startInterval = [startTime doubleValue] / 1000; // strip millis
NSDate *myStartDate = [NSDate dateWithTimeIntervalSince1970:_startInterval];
NSDate* myEndDate;
if ([endTime doubleValue] > 0) {
NSTimeInterval _endInterval = [endTime doubleValue] / 1000; // strip millis
myEndDate = [NSDate dateWithTimeIntervalSince1970:_endInterval];
} else {
// an enddate is mandatory for iOS, so using now+1y if it's not passed in
NSDateComponents *oneYearFromNowComponents = [[NSDateComponents alloc] init];
oneYearFromNowComponents.year = 1;
myEndDate = [[NSCalendar currentCalendar] dateByAddingComponents:oneYearFromNowComponents
toDate:[NSDate date]
options:0];
}
NSArray* calendars = nil;
if (calendarName == (id)[NSNull null]) {
calendars = [self.eventStore calendarsForEntityType:EKEntityTypeEvent];
if (calendars.count == 0) {
CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"No default calendar found. Is access to the Calendar blocked for this app?"];
[self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
return;
}
} else {
EKCalendar * calendar = [self findEKCalendar:calendarName];
if (calendar == nil) {
CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Could not find calendar"];
[self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
return;
} else {
calendars = [NSArray arrayWithObject:calendar];
}
}
// Find matches
EKCalendarItem *theEvent;
if (calEventID != nil) {
theEvent = [self.eventStore calendarItemWithIdentifier:calEventID];
}
NSArray *matchingEvents;
if (theEvent == nil) {
matchingEvents = [self findEKEventsWithTitle:title location:location notes:notes startDate:myStartDate endDate:myEndDate calendars:calendars];
} else {
matchingEvents = [NSArray arrayWithObject:theEvent];
}
NSMutableArray * eventsDataArray = [self eventsToDataArray:matchingEvents];
CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus: CDVCommandStatus_OK messageAsArray:eventsDataArray];
[self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}];
}
- (void) createCalendar:(CDVInvokedUrlCommand*)command {
NSDictionary* options = [command.arguments objectAtIndex:0];
NSString* calendarName = [options objectForKey:@"calendarName"];
NSString* hexColor = [options objectForKey:@"calendarColor"];
[self.commandDelegate runInBackground: ^{
EKCalendar *cal = [self findEKCalendar:calendarName];
CDVPluginResult* pluginResult = nil;
if (cal == nil) {
cal = [EKCalendar calendarForEntityType:EKEntityTypeEvent eventStore:self.eventStore];
cal.title = calendarName;
if (hexColor != (id)[NSNull null]) {
UIColor *theColor = [self colorFromHexString:hexColor];
cal.CGColor = theColor.CGColor;
}
cal.source = [self findEKSource];
// if the user did not allow permission to access the calendar, the error Object will be filled
NSError* error;
[self.eventStore saveCalendar:cal commit:YES error:&error];
if (error == nil) {
NSLog(@"created calendar: %@", cal.title);
pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:cal.calendarIdentifier];
} else {
NSLog(@"could not create calendar, error: %@", error.description);
pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Calendar could not be created. Is access to the Calendar blocked for this app?"];
}
} else {
// ok, it already exists
pluginResult = [CDVPluginResult resultWithStatus: CDVCommandStatus_OK messageAsString:@"OK, Calendar already exists"];
}
[self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}];
}
// Assumes input like "#00FF00" (#RRGGBB)
- (UIColor*) colorFromHexString:(NSString*) hexString {
unsigned rgbValue = 0;
NSScanner *scanner = [NSScanner scannerWithString:hexString];
[scanner setScanLocation:1]; // bypass '#' character
[scanner scanHexInt:&rgbValue];
return [UIColor colorWithRed:((rgbValue & 0xFF0000) >> 16) / 255.0 green:((rgbValue & 0xFF00) >> 8) / 255.0 blue:(rgbValue & 0xFF) / 255.0 alpha:1.0];
}
- (void) deleteCalendar:(CDVInvokedUrlCommand*)command {
NSDictionary* options = [command.arguments objectAtIndex:0];
NSString* calendarName = [options objectForKey:@"calendarName"];
[self.commandDelegate runInBackground: ^{
EKCalendar *thisCalendar = [self findEKCalendar:calendarName];
CDVPluginResult* pluginResult = nil;
if (thisCalendar == nil) {
pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_NO_RESULT];
} else {
NSError *error;
[eventStore removeCalendar:thisCalendar commit:YES error:&error];
if (error) {
NSLog(@"Error in deleteCalendar: %@", error.localizedDescription);
pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:error.userInfo.description];
} else {
pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];
}
}
[self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}];
}
- (void) eventEditViewController:(EKEventEditViewController*)controller didCompleteWithAction:(EKEventEditViewAction) action {
NSError *error = nil;
CDVPluginResult *pluginResult = nil;
switch (action) {
case EKEventEditViewActionCanceled:
pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_NO_RESULT];
break;
case EKEventEditViewActionSaved:
[controller.eventStore saveEvent:controller.event span:EKSpanThisEvent error:&error];
pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:controller.event.calendarItemIdentifier];
break;
case EKEventEditViewActionDeleted:
pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_NO_RESULT];
break;
default:
pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_NO_RESULT];
break;
}
[controller dismissViewControllerAnimated:YES completion:nil];
if (error) {
pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:error.userInfo.description];
}
[self.commandDelegate sendPluginResult:pluginResult callbackId:self.interactiveCallbackId];
}
/* There is no distingtion between read and write access in iOS */
- (void)hasReadPermission:(CDVInvokedUrlCommand*)command {
CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsBool:(self.eventStore != nil)];
[self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}
- (void)requestReadPermission:(CDVInvokedUrlCommand*)command {
CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:[self requestCalendarAccess]];
[self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}
- (void)hasWritePermission:(CDVInvokedUrlCommand*)command {
CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsBool:(self.eventStore != nil)];
[self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}
- (void)requestWritePermission:(CDVInvokedUrlCommand*)command {
CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:[self requestCalendarAccess]];
[self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}
- (void)hasReadWritePermission:(CDVInvokedUrlCommand*)command {
CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsBool:(self.eventStore != nil)];
[self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}
- (void)requestReadWritePermission:(CDVInvokedUrlCommand*)command {
CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:[self requestCalendarAccess]];
[self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}
-(CDVCommandStatus)requestCalendarAccess{
[self initEventStoreWithCalendarCapabilities];
return (self.eventStore != nil) ? CDVCommandStatus_OK : CDVCommandStatus_ERROR;
}
@end