-
Notifications
You must be signed in to change notification settings - Fork 279
/
Copy pathSwiftDeviceCalendarPlugin.swift
1005 lines (873 loc) · 38.9 KB
/
SwiftDeviceCalendarPlugin.swift
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
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import EventKit
import EventKitUI
import Flutter
import Foundation
import UIKit
extension Date {
var millisecondsSinceEpoch: Double { return self.timeIntervalSince1970 * 1000.0 }
}
extension EKParticipant {
var emailAddress: String? {
return self.value(forKey: "emailAddress") as? String
}
}
public class SwiftDeviceCalendarPlugin: NSObject, FlutterPlugin, EKEventViewDelegate, UINavigationControllerDelegate {
struct Calendar: Codable {
let id: String
let name: String
let isReadOnly: Bool
let isDefault: Bool
let color: Int
let accountName: String
let accountType: String
}
struct Event: Codable {
let eventId: String
let calendarId: String
let eventTitle: String
let eventDescription: String?
let eventStartDate: Int64
let eventEndDate: Int64
let eventStartTimeZone: String?
let eventAllDay: Bool
let attendees: [Attendee]
let eventLocation: String?
let eventURL: String?
let recurrenceRule: RecurrenceRule?
let organizer: Attendee?
let reminders: [Reminder]
let availability: Availability?
let eventStatus: EventStatus?
}
struct RecurrenceRule: Codable {
let recurrenceFrequency: Int
let totalOccurrences: Int?
let interval: Int
let endDate: Int64?
let daysOfWeek: [Int]?
let dayOfMonth: Int?
let monthOfYear: Int?
let weekOfMonth: Int?
}
struct Attendee: Codable {
let name: String?
let emailAddress: String
let role: Int
let attendanceStatus: Int
let isCurrentUser: Bool
}
struct Reminder: Codable {
let minutes: Int
}
enum Availability: String, Codable {
case BUSY
case FREE
case TENTATIVE
case UNAVAILABLE
}
enum EventStatus: String, Codable {
case CONFIRMED
case TENTATIVE
case CANCELED
case NONE
}
static let channelName = "plugins.builttoroam.com/device_calendar"
let notFoundErrorCode = "404"
let notAllowed = "405"
let genericError = "500"
let unauthorizedErrorCode = "401"
let unauthorizedErrorMessage = "The user has not allowed this application to modify their calendar(s)"
let calendarNotFoundErrorMessageFormat = "The calendar with the ID %@ could not be found"
let calendarReadOnlyErrorMessageFormat = "Calendar with ID %@ is read-only"
let eventNotFoundErrorMessageFormat = "The event with the ID %@ could not be found"
let eventStore = EKEventStore()
let requestPermissionsMethod = "requestPermissions"
let hasPermissionsMethod = "hasPermissions"
let retrieveCalendarsMethod = "retrieveCalendars"
let retrieveEventsMethod = "retrieveEvents"
let retrieveSourcesMethod = "retrieveSources"
let createOrUpdateEventMethod = "createOrUpdateEvent"
let createCalendarMethod = "createCalendar"
let deleteCalendarMethod = "deleteCalendar"
let deleteEventMethod = "deleteEvent"
let deleteEventInstanceMethod = "deleteEventInstance"
let showEventModalMethod = "showiOSEventModal"
let calendarIdArgument = "calendarId"
let startDateArgument = "startDate"
let endDateArgument = "endDate"
let eventIdArgument = "eventId"
let eventIdsArgument = "eventIds"
let eventTitleArgument = "eventTitle"
let eventDescriptionArgument = "eventDescription"
let eventAllDayArgument = "eventAllDay"
let eventStartDateArgument = "eventStartDate"
let eventEndDateArgument = "eventEndDate"
let eventStartTimeZoneArgument = "eventStartTimeZone"
let eventLocationArgument = "eventLocation"
let eventURLArgument = "eventURL"
let attendeesArgument = "attendees"
let recurrenceRuleArgument = "recurrenceRule"
let recurrenceFrequencyArgument = "recurrenceFrequency"
let totalOccurrencesArgument = "totalOccurrences"
let intervalArgument = "interval"
let daysOfWeekArgument = "daysOfWeek"
let dayOfMonthArgument = "dayOfMonth"
let monthOfYearArgument = "monthOfYear"
let weekOfMonthArgument = "weekOfMonth"
let nameArgument = "name"
let emailAddressArgument = "emailAddress"
let roleArgument = "role"
let remindersArgument = "reminders"
let minutesArgument = "minutes"
let followingInstancesArgument = "followingInstances"
let calendarNameArgument = "calendarName"
let calendarColorArgument = "calendarColor"
let availabilityArgument = "availability"
let attendanceStatusArgument = "attendanceStatus"
let eventStatusArgument = "eventStatus"
let validFrequencyTypes = [EKRecurrenceFrequency.daily, EKRecurrenceFrequency.weekly, EKRecurrenceFrequency.monthly, EKRecurrenceFrequency.yearly]
var flutterResult : FlutterResult?
public static func register(with registrar: FlutterPluginRegistrar) {
let channel = FlutterMethodChannel(name: channelName, binaryMessenger: registrar.messenger())
let instance = SwiftDeviceCalendarPlugin()
registrar.addMethodCallDelegate(instance, channel: channel)
}
public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
switch call.method {
case requestPermissionsMethod:
requestPermissions(result)
case hasPermissionsMethod:
hasPermissions(result)
case retrieveCalendarsMethod:
retrieveCalendars(result)
case retrieveEventsMethod:
retrieveEvents(call, result)
case createOrUpdateEventMethod:
createOrUpdateEvent(call, result)
case deleteEventMethod:
deleteEvent(call, result)
case deleteEventInstanceMethod:
deleteEvent(call, result)
case createCalendarMethod:
createCalendar(call, result)
case deleteCalendarMethod:
deleteCalendar(call, result)
case showEventModalMethod:
self.flutterResult = result
showEventModal(call, result)
default:
result(FlutterMethodNotImplemented)
}
}
private func hasPermissions(_ result: FlutterResult) {
let hasPermissions = hasEventPermissions()
result(hasPermissions)
}
private func getSource() -> EKSource? {
let localSources = eventStore.sources.filter { $0.sourceType == .local }
if (!localSources.isEmpty) {
return localSources.first
}
if let defaultSource = eventStore.defaultCalendarForNewEvents?.source {
return defaultSource
}
let iCloudSources = eventStore.sources.filter { $0.sourceType == .calDAV && $0.sourceIdentifier == "iCloud" }
if (!iCloudSources.isEmpty) {
return iCloudSources.first
}
return nil
}
private func createCalendar(_ call: FlutterMethodCall, _ result: FlutterResult) {
let arguments = call.arguments as! Dictionary<String, AnyObject>
let calendar = EKCalendar.init(for: EKEntityType.event, eventStore: eventStore)
do {
calendar.title = arguments[calendarNameArgument] as! String
let calendarColor = arguments[calendarColorArgument] as? String
if (calendarColor != nil) {
calendar.cgColor = UIColor(hex: calendarColor!)?.cgColor
}
else {
calendar.cgColor = UIColor(red: 255, green: 0, blue: 0, alpha: 0).cgColor // Red colour as a default
}
guard let source = getSource() else {
result(FlutterError(code: self.genericError, message: "Local calendar was not found.", details: nil))
return
}
calendar.source = source
try eventStore.saveCalendar(calendar, commit: true)
result(calendar.calendarIdentifier)
}
catch {
eventStore.reset()
result(FlutterError(code: self.genericError, message: error.localizedDescription, details: nil))
}
}
private func retrieveCalendars(_ result: @escaping FlutterResult) {
checkPermissionsThenExecute(permissionsGrantedAction: {
let ekCalendars = self.eventStore.calendars(for: .event)
let defaultCalendar = self.eventStore.defaultCalendarForNewEvents
var calendars = [Calendar]()
for ekCalendar in ekCalendars {
let calendar = Calendar(
id: ekCalendar.calendarIdentifier,
name: ekCalendar.title,
isReadOnly: !ekCalendar.allowsContentModifications,
isDefault: defaultCalendar?.calendarIdentifier == ekCalendar.calendarIdentifier,
color: UIColor(cgColor: ekCalendar.cgColor).rgb()!,
accountName: ekCalendar.source.title,
accountType: getAccountType(ekCalendar.source.sourceType))
calendars.append(calendar)
}
self.encodeJsonAndFinish(codable: calendars, result: result)
}, result: result)
}
private func deleteCalendar(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) {
checkPermissionsThenExecute(permissionsGrantedAction: {
let arguments = call.arguments as! Dictionary<String, AnyObject>
let calendarId = arguments[calendarIdArgument] as! String
let ekCalendar = self.eventStore.calendar(withIdentifier: calendarId)
if ekCalendar == nil {
self.finishWithCalendarNotFoundError(result: result, calendarId: calendarId)
return
}
if !(ekCalendar!.allowsContentModifications) {
self.finishWithCalendarReadOnlyError(result: result, calendarId: calendarId)
return
}
do {
try self.eventStore.removeCalendar(ekCalendar!, commit: true)
result(true)
} catch {
self.eventStore.reset()
result(FlutterError(code: self.genericError, message: error.localizedDescription, details: nil))
}
}, result: result)
}
private func getAccountType(_ sourceType: EKSourceType) -> String {
switch (sourceType) {
case .local:
return "Local";
case .exchange:
return "Exchange";
case .calDAV:
return "CalDAV";
case .mobileMe:
return "MobileMe";
case .subscribed:
return "Subscribed";
case .birthdays:
return "Birthdays";
default:
return "Unknown";
}
}
private func retrieveEvents(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) {
checkPermissionsThenExecute(permissionsGrantedAction: {
let arguments = call.arguments as! Dictionary<String, AnyObject>
let calendarId = arguments[calendarIdArgument] as! String
let startDateMillisecondsSinceEpoch = arguments[startDateArgument] as? NSNumber
let endDateDateMillisecondsSinceEpoch = arguments[endDateArgument] as? NSNumber
let eventIdArgs = arguments[eventIdsArgument] as? [String]
var events = [Event]()
let specifiedStartEndDates = startDateMillisecondsSinceEpoch != nil && endDateDateMillisecondsSinceEpoch != nil
if specifiedStartEndDates {
let startDate = Date (timeIntervalSince1970: startDateMillisecondsSinceEpoch!.doubleValue / 1000.0)
let endDate = Date (timeIntervalSince1970: endDateDateMillisecondsSinceEpoch!.doubleValue / 1000.0)
let ekCalendar = self.eventStore.calendar(withIdentifier: calendarId)
if ekCalendar != nil {
let predicate = self.eventStore.predicateForEvents(
withStart: startDate,
end: endDate,
calendars: [ekCalendar!])
let ekEvents = self.eventStore.events(matching: predicate)
for ekEvent in ekEvents {
let event = createEventFromEkEvent(calendarId: calendarId, ekEvent: ekEvent)
events.append(event)
}
}
}
guard let eventIds = eventIdArgs else {
self.encodeJsonAndFinish(codable: events, result: result)
return
}
if specifiedStartEndDates {
events = events.filter({ (e) -> Bool in
e.calendarId == calendarId && eventIds.contains(e.eventId)
})
self.encodeJsonAndFinish(codable: events, result: result)
return
}
for eventId in eventIds {
let ekEvent = self.eventStore.event(withIdentifier: eventId)
if ekEvent == nil {
continue
}
let event = createEventFromEkEvent(calendarId: calendarId, ekEvent: ekEvent!)
events.append(event)
}
self.encodeJsonAndFinish(codable: events, result: result)
}, result: result)
}
private func createEventFromEkEvent(calendarId: String, ekEvent: EKEvent) -> Event {
var attendees = [Attendee]()
if ekEvent.attendees != nil {
for ekParticipant in ekEvent.attendees! {
let attendee = convertEkParticipantToAttendee(ekParticipant: ekParticipant)
if attendee == nil {
continue
}
attendees.append(attendee!)
}
}
var reminders = [Reminder]()
if ekEvent.alarms != nil {
for alarm in ekEvent.alarms! {
reminders.append(Reminder(minutes: Int(-alarm.relativeOffset / 60)))
}
}
let recurrenceRule = parseEKRecurrenceRules(ekEvent)
let event = Event(
eventId: ekEvent.eventIdentifier,
calendarId: calendarId,
eventTitle: ekEvent.title ?? "New Event",
eventDescription: ekEvent.notes,
eventStartDate: Int64(ekEvent.startDate.millisecondsSinceEpoch),
eventEndDate: Int64(ekEvent.endDate.millisecondsSinceEpoch),
eventStartTimeZone: ekEvent.timeZone?.identifier,
eventAllDay: ekEvent.isAllDay,
attendees: attendees,
eventLocation: ekEvent.location,
eventURL: ekEvent.url?.absoluteString,
recurrenceRule: recurrenceRule,
organizer: convertEkParticipantToAttendee(ekParticipant: ekEvent.organizer),
reminders: reminders,
availability: convertEkEventAvailability(ekEventAvailability: ekEvent.availability),
eventStatus: convertEkEventStatus(ekEventStatus: ekEvent.status)
)
return event
}
private func convertEkParticipantToAttendee(ekParticipant: EKParticipant?) -> Attendee? {
if ekParticipant == nil || ekParticipant?.emailAddress == nil {
return nil
}
let attendee = Attendee(
name: ekParticipant!.name,
emailAddress: ekParticipant!.emailAddress!,
role: ekParticipant!.participantRole.rawValue,
attendanceStatus: ekParticipant!.participantStatus.rawValue,
isCurrentUser: ekParticipant!.isCurrentUser
)
return attendee
}
private func convertEkEventAvailability(ekEventAvailability: EKEventAvailability?) -> Availability? {
switch ekEventAvailability {
case .busy:
return Availability.BUSY
case .free:
return Availability.FREE
case .tentative:
return Availability.TENTATIVE
case .unavailable:
return Availability.UNAVAILABLE
default:
return nil
}
}
private func convertEkEventStatus(ekEventStatus: EKEventStatus?) -> EventStatus? {
switch ekEventStatus {
case .confirmed:
return EventStatus.CONFIRMED
case .tentative:
return EventStatus.TENTATIVE
case .canceled:
return EventStatus.CANCELED
case .none?:
return EventStatus.NONE
default:
return nil
}
}
private func parseEKRecurrenceRules(_ ekEvent: EKEvent) -> RecurrenceRule? {
var recurrenceRule: RecurrenceRule?
if ekEvent.hasRecurrenceRules {
let ekRecurrenceRule = ekEvent.recurrenceRules![0]
var frequency: Int
switch ekRecurrenceRule.frequency {
case EKRecurrenceFrequency.daily:
frequency = 0
case EKRecurrenceFrequency.weekly:
frequency = 1
case EKRecurrenceFrequency.monthly:
frequency = 2
case EKRecurrenceFrequency.yearly:
frequency = 3
default:
frequency = 0
}
var totalOccurrences: Int?
var endDate: Int64?
if(ekRecurrenceRule.recurrenceEnd?.occurrenceCount != nil && ekRecurrenceRule.recurrenceEnd?.occurrenceCount != 0) {
totalOccurrences = ekRecurrenceRule.recurrenceEnd?.occurrenceCount
}
let endDateMs = ekRecurrenceRule.recurrenceEnd?.endDate?.millisecondsSinceEpoch
if(endDateMs != nil) {
endDate = Int64(exactly: endDateMs!)
}
var weekOfMonth = ekRecurrenceRule.setPositions?.first?.intValue
var daysOfWeek: [Int]?
if ekRecurrenceRule.daysOfTheWeek != nil && !ekRecurrenceRule.daysOfTheWeek!.isEmpty {
daysOfWeek = []
for dayOfWeek in ekRecurrenceRule.daysOfTheWeek! {
daysOfWeek!.append(dayOfWeek.dayOfTheWeek.rawValue - 1)
if weekOfMonth == nil {
weekOfMonth = dayOfWeek.weekNumber
}
}
}
// For recurrence of nth day of nth month every year, no calendar parameters are given
// So we need to explicitly set them from event start date
var dayOfMonth = ekRecurrenceRule.daysOfTheMonth?.first?.intValue
var monthOfYear = ekRecurrenceRule.monthsOfTheYear?.first?.intValue
if (ekRecurrenceRule.frequency == EKRecurrenceFrequency.yearly
&& weekOfMonth == nil && dayOfMonth == nil && monthOfYear == nil) {
let dateFormatter = DateFormatter()
// Setting day of the month
dateFormatter.dateFormat = "d"
dayOfMonth = Int(dateFormatter.string(from: ekEvent.startDate))
// Setting month of the year
dateFormatter.dateFormat = "M"
monthOfYear = Int(dateFormatter.string(from: ekEvent.startDate))
}
recurrenceRule = RecurrenceRule(
recurrenceFrequency: frequency,
totalOccurrences: totalOccurrences,
interval: ekRecurrenceRule.interval,
endDate: endDate,
daysOfWeek: daysOfWeek,
dayOfMonth: dayOfMonth,
monthOfYear: monthOfYear,
weekOfMonth: weekOfMonth)
}
return recurrenceRule
}
private func createEKRecurrenceRules(_ arguments: [String : AnyObject]) -> [EKRecurrenceRule]?{
let recurrenceRuleArguments = arguments[recurrenceRuleArgument] as? Dictionary<String, AnyObject>
if recurrenceRuleArguments == nil {
return nil
}
let recurrenceFrequencyIndex = recurrenceRuleArguments![recurrenceFrequencyArgument] as? NSInteger
let totalOccurrences = recurrenceRuleArguments![totalOccurrencesArgument] as? NSInteger
let interval = recurrenceRuleArguments![intervalArgument] as? NSInteger
var recurrenceInterval = 1
let endDate = recurrenceRuleArguments![endDateArgument] as? NSNumber
let namedFrequency = validFrequencyTypes[recurrenceFrequencyIndex!]
var recurrenceEnd:EKRecurrenceEnd?
if endDate != nil {
recurrenceEnd = EKRecurrenceEnd(end: Date.init(timeIntervalSince1970: endDate!.doubleValue / 1000))
} else if(totalOccurrences != nil && totalOccurrences! > 0) {
recurrenceEnd = EKRecurrenceEnd(occurrenceCount: totalOccurrences!)
}
if interval != nil && interval! > 1 {
recurrenceInterval = interval!
}
let daysOfWeekIndices = recurrenceRuleArguments![daysOfWeekArgument] as? [Int]
var daysOfWeek : [EKRecurrenceDayOfWeek]?
if daysOfWeekIndices != nil && !daysOfWeekIndices!.isEmpty {
daysOfWeek = []
for dayOfWeekIndex in daysOfWeekIndices! {
// Append week number to BYDAY for yearly or monthly with 'last' week number
if let weekOfMonth = recurrenceRuleArguments![weekOfMonthArgument] as? Int {
if namedFrequency == EKRecurrenceFrequency.yearly || weekOfMonth == -1 {
daysOfWeek!.append(EKRecurrenceDayOfWeek.init(
dayOfTheWeek: EKWeekday.init(rawValue: dayOfWeekIndex + 1)!,
weekNumber: weekOfMonth
))
}
} else {
daysOfWeek!.append(EKRecurrenceDayOfWeek.init(EKWeekday.init(rawValue: dayOfWeekIndex + 1)!))
}
}
}
var dayOfMonthArray : [NSNumber]?
if let dayOfMonth = recurrenceRuleArguments![dayOfMonthArgument] as? Int {
dayOfMonthArray = []
dayOfMonthArray!.append(NSNumber(value: dayOfMonth))
}
var monthOfYearArray : [NSNumber]?
if let monthOfYear = recurrenceRuleArguments![monthOfYearArgument] as? Int {
monthOfYearArray = []
monthOfYearArray!.append(NSNumber(value: monthOfYear))
}
// Append BYSETPOS only on monthly (but not last), yearly's week number (and last for monthly) appends to BYDAY
var weekOfMonthArray : [NSNumber]?
if namedFrequency == EKRecurrenceFrequency.monthly {
if let weekOfMonth = recurrenceRuleArguments![weekOfMonthArgument] as? Int {
if weekOfMonth != -1 {
weekOfMonthArray = []
weekOfMonthArray!.append(NSNumber(value: weekOfMonth))
}
}
}
return [EKRecurrenceRule(
recurrenceWith: namedFrequency,
interval: recurrenceInterval,
daysOfTheWeek: daysOfWeek,
daysOfTheMonth: dayOfMonthArray,
monthsOfTheYear: monthOfYearArray,
weeksOfTheYear: nil,
daysOfTheYear: nil,
setPositions: weekOfMonthArray,
end: recurrenceEnd)]
}
private func setAttendees(_ arguments: [String : AnyObject], _ ekEvent: EKEvent?) {
let attendeesArguments = arguments[attendeesArgument] as? [Dictionary<String, AnyObject>]
if attendeesArguments == nil {
return
}
var attendees = [EKParticipant]()
for attendeeArguments in attendeesArguments! {
let name = attendeeArguments[nameArgument] as! String
let emailAddress = attendeeArguments[emailAddressArgument] as! String
let role = attendeeArguments[roleArgument] as! Int
if (ekEvent!.attendees != nil) {
let existingAttendee = ekEvent!.attendees!.first { element in
return element.emailAddress == emailAddress
}
if existingAttendee != nil && ekEvent!.organizer?.emailAddress != existingAttendee?.emailAddress{
attendees.append(existingAttendee!)
continue
}
}
let attendee = createParticipant(
name: name,
emailAddress: emailAddress,
role: role)
if (attendee == nil) {
continue
}
attendees.append(attendee!)
}
ekEvent!.setValue(attendees, forKey: "attendees")
}
private func createReminders(_ arguments: [String : AnyObject]) -> [EKAlarm]?{
let remindersArguments = arguments[remindersArgument] as? [Dictionary<String, AnyObject>]
if remindersArguments == nil {
return nil
}
var reminders = [EKAlarm]()
for reminderArguments in remindersArguments! {
let minutes = reminderArguments[minutesArgument] as! Int
reminders.append(EKAlarm.init(relativeOffset: 60 * Double(-minutes)))
}
return reminders
}
private func setAvailability(_ arguments: [String : AnyObject]) -> EKEventAvailability? {
guard let availabilityValue = arguments[availabilityArgument] as? String else {
return .unavailable
}
switch availabilityValue.uppercased() {
case Availability.BUSY.rawValue:
return .busy
case Availability.FREE.rawValue:
return .free
case Availability.TENTATIVE.rawValue:
return .tentative
case Availability.UNAVAILABLE.rawValue:
return .unavailable
default:
return nil
}
}
private func createOrUpdateEvent(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) {
checkPermissionsThenExecute(permissionsGrantedAction: {
let arguments = call.arguments as! Dictionary<String, AnyObject>
let calendarId = arguments[calendarIdArgument] as! String
let eventId = arguments[eventIdArgument] as? String
let isAllDay = arguments[eventAllDayArgument] as! Bool
let startDateMillisecondsSinceEpoch = arguments[eventStartDateArgument] as! NSNumber
let endDateDateMillisecondsSinceEpoch = arguments[eventEndDateArgument] as! NSNumber
let startDate = Date (timeIntervalSince1970: startDateMillisecondsSinceEpoch.doubleValue / 1000.0)
let endDate = Date (timeIntervalSince1970: endDateDateMillisecondsSinceEpoch.doubleValue / 1000.0)
let startTimeZoneString = arguments[eventStartTimeZoneArgument] as? String
let title = arguments[self.eventTitleArgument] as! String
let description = arguments[self.eventDescriptionArgument] as? String
let location = arguments[self.eventLocationArgument] as? String
let url = arguments[self.eventURLArgument] as? String
let ekCalendar = self.eventStore.calendar(withIdentifier: calendarId)
if (ekCalendar == nil) {
self.finishWithCalendarNotFoundError(result: result, calendarId: calendarId)
return
}
if !(ekCalendar!.allowsContentModifications) {
self.finishWithCalendarReadOnlyError(result: result, calendarId: calendarId)
return
}
var ekEvent: EKEvent?
if eventId == nil {
ekEvent = EKEvent.init(eventStore: self.eventStore)
} else {
ekEvent = self.eventStore.event(withIdentifier: eventId!)
if(ekEvent == nil) {
self.finishWithEventNotFoundError(result: result, eventId: eventId!)
return
}
}
ekEvent!.title = title
ekEvent!.notes = description
ekEvent!.isAllDay = isAllDay
ekEvent!.startDate = startDate
ekEvent!.endDate = endDate
if (!isAllDay) {
let timeZone = TimeZone(identifier: startTimeZoneString ?? TimeZone.current.identifier) ?? .current
ekEvent!.timeZone = timeZone
}
ekEvent!.calendar = ekCalendar!
ekEvent!.location = location
// Create and add URL object only when if the input string is not empty or nil
if let urlCheck = url, !urlCheck.isEmpty {
let iosUrl = URL(string: url ?? "")
ekEvent!.url = iosUrl
}
else {
ekEvent!.url = nil
}
ekEvent!.recurrenceRules = createEKRecurrenceRules(arguments)
setAttendees(arguments, ekEvent)
ekEvent!.alarms = createReminders(arguments)
if let availability = setAvailability(arguments) {
ekEvent!.availability = availability
}
do {
try self.eventStore.save(ekEvent!, span: .futureEvents)
result(ekEvent!.eventIdentifier)
} catch {
self.eventStore.reset()
result(FlutterError(code: self.genericError, message: error.localizedDescription, details: nil))
}
}, result: result)
}
private func createParticipant(name: String, emailAddress: String, role: Int) -> EKParticipant? {
let ekAttendeeClass: AnyClass? = NSClassFromString("EKAttendee")
if let type = ekAttendeeClass as? NSObject.Type {
let participant = type.init()
participant.setValue(UUID().uuidString, forKey: "UUID")
participant.setValue(name, forKey: "displayName")
participant.setValue(emailAddress, forKey: "emailAddress")
participant.setValue(role, forKey: "participantRole")
return participant as? EKParticipant
}
return nil
}
private func deleteEvent(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) {
checkPermissionsThenExecute(permissionsGrantedAction: {
let arguments = call.arguments as! Dictionary<String, AnyObject>
let calendarId = arguments[calendarIdArgument] as! String
let eventId = arguments[eventIdArgument] as! String
let startDateNumber = arguments[eventStartDateArgument] as? NSNumber
let endDateNumber = arguments[eventEndDateArgument] as? NSNumber
let followingInstances = arguments[followingInstancesArgument] as? Bool
let ekCalendar = self.eventStore.calendar(withIdentifier: calendarId)
if ekCalendar == nil {
self.finishWithCalendarNotFoundError(result: result, calendarId: calendarId)
return
}
if !(ekCalendar!.allowsContentModifications) {
self.finishWithCalendarReadOnlyError(result: result, calendarId: calendarId)
return
}
if (startDateNumber == nil && endDateNumber == nil && followingInstances == nil) {
let ekEvent = self.eventStore.event(withIdentifier: eventId)
if ekEvent == nil {
self.finishWithEventNotFoundError(result: result, eventId: eventId)
return
}
do {
try self.eventStore.remove(ekEvent!, span: .futureEvents)
result(true)
} catch {
self.eventStore.reset()
result(FlutterError(code: self.genericError, message: error.localizedDescription, details: nil))
}
}
else {
let startDate = Date (timeIntervalSince1970: startDateNumber!.doubleValue / 1000.0)
let endDate = Date (timeIntervalSince1970: endDateNumber!.doubleValue / 1000.0)
let predicate = self.eventStore.predicateForEvents(withStart: startDate, end: endDate, calendars: nil)
let foundEkEvents = self.eventStore.events(matching: predicate) as [EKEvent]?
if foundEkEvents == nil || foundEkEvents?.count == 0 {
self.finishWithEventNotFoundError(result: result, eventId: eventId)
return
}
let ekEvent = foundEkEvents!.first(where: {$0.eventIdentifier == eventId})
do {
if (!followingInstances!) {
try self.eventStore.remove(ekEvent!, span: .thisEvent, commit: true)
}
else {
try self.eventStore.remove(ekEvent!, span: .futureEvents, commit: true)
}
result(true)
} catch {
self.eventStore.reset()
result(FlutterError(code: self.genericError, message: error.localizedDescription, details: nil))
}
}
}, result: result)
}
private func showEventModal(_ call: FlutterMethodCall, _ result: @escaping FlutterResult) {
checkPermissionsThenExecute(permissionsGrantedAction: {
let arguments = call.arguments as! Dictionary<String, AnyObject>
let eventId = arguments[eventIdArgument] as! String
let event = self.eventStore.event(withIdentifier: eventId)
if event != nil {
let eventController = EKEventViewController()
eventController.event = event!
eventController.delegate = self
eventController.allowsEditing = true
eventController.allowsCalendarPreview = true
let flutterViewController = getTopMostViewController()
let navigationController = UINavigationController(rootViewController: eventController)
navigationController.toolbar.isTranslucent = false
navigationController.toolbar.tintColor = .blue
navigationController.toolbar.backgroundColor = .white
flutterViewController.present(navigationController, animated: true, completion: nil)
} else {
result(FlutterError(code: self.genericError, message: self.eventNotFoundErrorMessageFormat, details: nil))
}
}, result: result)
}
public func eventViewController(_ controller: EKEventViewController, didCompleteWith action: EKEventViewAction) {
controller.dismiss(animated: true, completion: nil)
if flutterResult != nil {
switch action {
case .done:
flutterResult!(nil)
case .responded:
flutterResult!(nil)
case .deleted:
flutterResult!(nil)
@unknown default:
flutterResult!(nil)
}
}
}
private func getTopMostViewController() -> UIViewController {
var topController: UIViewController? = UIApplication.shared.keyWindow?.rootViewController
while ((topController?.presentedViewController) != nil) {
topController = topController?.presentedViewController
}
return topController!
}
private func finishWithUnauthorizedError(result: @escaping FlutterResult) {
result(FlutterError(code:self.unauthorizedErrorCode, message: self.unauthorizedErrorMessage, details: nil))
}
private func finishWithCalendarNotFoundError(result: @escaping FlutterResult, calendarId: String) {
let errorMessage = String(format: self.calendarNotFoundErrorMessageFormat, calendarId)
result(FlutterError(code:self.notFoundErrorCode, message: errorMessage, details: nil))
}
private func finishWithCalendarReadOnlyError(result: @escaping FlutterResult, calendarId: String) {
let errorMessage = String(format: self.calendarReadOnlyErrorMessageFormat, calendarId)
result(FlutterError(code:self.notAllowed, message: errorMessage, details: nil))
}
private func finishWithEventNotFoundError(result: @escaping FlutterResult, eventId: String) {
let errorMessage = String(format: self.eventNotFoundErrorMessageFormat, eventId)
result(FlutterError(code:self.notFoundErrorCode, message: errorMessage, details: nil))
}
private func encodeJsonAndFinish<T: Codable>(codable: T, result: @escaping FlutterResult) {
do {
let jsonEncoder = JSONEncoder()
let jsonData = try jsonEncoder.encode(codable)
let jsonString = String(data: jsonData, encoding: .utf8)
result(jsonString)
} catch {
result(FlutterError(code: genericError, message: error.localizedDescription, details: nil))
}
}
private func checkPermissionsThenExecute(permissionsGrantedAction: () -> Void, result: @escaping FlutterResult) {
if hasEventPermissions() {
permissionsGrantedAction()
return
}
self.finishWithUnauthorizedError(result: result)
}
private func requestPermissions(completion: @escaping (Bool) -> Void) {
if hasEventPermissions() {
completion(true)
return
}
if #available(iOS 17, *) {
eventStore.requestFullAccessToEvents {
(accessGranted: Bool, _: Error?) in
completion(accessGranted)
}
} else {
eventStore.requestAccess(to: .event, completion: {
(accessGranted: Bool, _: Error?) in
completion(accessGranted)
})
}
}
private func hasEventPermissions() -> Bool {
let status = EKEventStore.authorizationStatus(for: .event)
if #available(iOS 17, *) {
return status == EKAuthorizationStatus.fullAccess
} else {
return status == EKAuthorizationStatus.authorized
}
}
private func requestPermissions(_ result: @escaping FlutterResult) {
if hasEventPermissions() {
result(true)
}
eventStore.requestAccess(to: .event, completion: {
(accessGranted: Bool, _: Error?) in
result(accessGranted)
})
}
}
extension Date {
func convert(from initTimeZone: TimeZone, to targetTimeZone: TimeZone) -> Date {
let delta = TimeInterval(initTimeZone.secondsFromGMT() - targetTimeZone.secondsFromGMT())
return addingTimeInterval(delta)
}
}
extension UIColor {
func rgb() -> Int? {
var fRed : CGFloat = 0
var fGreen : CGFloat = 0
var fBlue : CGFloat = 0
var fAlpha: CGFloat = 0
if self.getRed(&fRed, green: &fGreen, blue: &fBlue, alpha: &fAlpha) {
let iRed = Int(fRed * 255.0)
let iGreen = Int(fGreen * 255.0)
let iBlue = Int(fBlue * 255.0)
let iAlpha = Int(fAlpha * 255.0)
// (Bits 24-31 are alpha, 16-23 are red, 8-15 are green, 0-7 are blue).
let rgb = (iAlpha << 24) + (iRed << 16) + (iGreen << 8) + iBlue
return rgb
} else {
// Could not extract RGBA components:
return nil
}
}
public convenience init?(hex: String) {
let r, g, b, a: CGFloat
if hex.hasPrefix("0x") {
let start = hex.index(hex.startIndex, offsetBy: 2)
let hexColor = String(hex[start...])
if hexColor.count == 8 {
let scanner = Scanner(string: hexColor)
var hexNumber: UInt64 = 0
if scanner.scanHexInt64(&hexNumber) {
a = CGFloat((hexNumber & 0xff000000) >> 24) / 255
r = CGFloat((hexNumber & 0x00ff0000) >> 16) / 255
g = CGFloat((hexNumber & 0x0000ff00) >> 8) / 255
b = CGFloat((hexNumber & 0x000000ff)) / 255
self.init(red: r, green: g, blue: b, alpha: a)
return
}
}