/
FlutterLocalNotificationsPlugin.m
1315 lines (1223 loc) · 54.4 KB
/
FlutterLocalNotificationsPlugin.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
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 "FlutterLocalNotificationsPlugin.h"
#import "ActionEventSink.h"
#import "Converters.h"
#import "FlutterEngineManager.h"
@implementation FlutterLocalNotificationsPlugin {
FlutterMethodChannel *_channel;
bool _displayAlert;
bool _playSound;
bool _updateBadge;
bool _initialized;
bool _launchingAppFromNotification;
NSObject<FlutterPluginRegistrar> *_registrar;
FlutterEngineManager *_flutterEngineManager;
NSMutableDictionary *_launchNotificationResponseDict;
}
static FlutterPluginRegistrantCallback registerPlugins;
static ActionEventSink *actionEventSink;
NSString *const FOREGROUND_ACTION_IDENTIFIERS =
@"dexterous.com/flutter/local_notifications/foreground_action_identifiers";
NSString *const INITIALIZE_METHOD = @"initialize";
NSString *const GET_CALLBACK_METHOD = @"getCallbackHandle";
NSString *const SHOW_METHOD = @"show";
NSString *const SCHEDULE_METHOD = @"schedule";
NSString *const ZONED_SCHEDULE_METHOD = @"zonedSchedule";
NSString *const PERIODICALLY_SHOW_METHOD = @"periodicallyShow";
NSString *const SHOW_DAILY_AT_TIME_METHOD = @"showDailyAtTime";
NSString *const SHOW_WEEKLY_AT_DAY_AND_TIME_METHOD = @"showWeeklyAtDayAndTime";
NSString *const CANCEL_METHOD = @"cancel";
NSString *const CANCEL_ALL_METHOD = @"cancelAll";
NSString *const PENDING_NOTIFICATIONS_REQUESTS_METHOD =
@"pendingNotificationRequests";
NSString *const GET_ACTIVE_NOTIFICATIONS_METHOD = @"getActiveNotifications";
NSString *const GET_NOTIFICATION_APP_LAUNCH_DETAILS_METHOD =
@"getNotificationAppLaunchDetails";
NSString *const CHANNEL = @"dexterous.com/flutter/local_notifications";
NSString *const CALLBACK_CHANNEL =
@"dexterous.com/flutter/local_notifications_background";
NSString *const ON_NOTIFICATION_METHOD = @"onNotification";
NSString *const DID_RECEIVE_LOCAL_NOTIFICATION = @"didReceiveLocalNotification";
NSString *const REQUEST_PERMISSIONS_METHOD = @"requestPermissions";
NSString *const DAY = @"day";
NSString *const REQUEST_SOUND_PERMISSION = @"requestSoundPermission";
NSString *const REQUEST_ALERT_PERMISSION = @"requestAlertPermission";
NSString *const REQUEST_BADGE_PERMISSION = @"requestBadgePermission";
NSString *const REQUEST_CRITICAL_PERMISSION = @"requestCriticalPermission";
NSString *const SOUND_PERMISSION = @"sound";
NSString *const ALERT_PERMISSION = @"alert";
NSString *const BADGE_PERMISSION = @"badge";
NSString *const CRITICAL_PERMISSION = @"critical";
NSString *const DEFAULT_PRESENT_ALERT = @"defaultPresentAlert";
NSString *const DEFAULT_PRESENT_SOUND = @"defaultPresentSound";
NSString *const DEFAULT_PRESENT_BADGE = @"defaultPresentBadge";
NSString *const CALLBACK_DISPATCHER = @"callbackDispatcher";
NSString *const ON_NOTIFICATION_CALLBACK_DISPATCHER =
@"onNotificationCallbackDispatcher";
NSString *const PLATFORM_SPECIFICS = @"platformSpecifics";
NSString *const ID = @"id";
NSString *const TITLE = @"title";
NSString *const SUBTITLE = @"subtitle";
NSString *const BODY = @"body";
NSString *const SOUND = @"sound";
NSString *const ATTACHMENTS = @"attachments";
NSString *const ATTACHMENT_IDENTIFIER = @"identifier";
NSString *const ATTACHMENT_FILE_PATH = @"filePath";
NSString *const ATTACHMENT_HIDE_THUMBNAIL = @"hideThumbnail";
NSString *const ATTACHMENT_THUMBNAIL_CLIPPING_RECT = @"thumbnailClippingRect";
NSString *const INTERRUPTION_LEVEL = @"interruptionLevel";
NSString *const THREAD_IDENTIFIER = @"threadIdentifier";
NSString *const PRESENT_ALERT = @"presentAlert";
NSString *const PRESENT_SOUND = @"presentSound";
NSString *const PRESENT_BADGE = @"presentBadge";
NSString *const BADGE_NUMBER = @"badgeNumber";
NSString *const MILLISECONDS_SINCE_EPOCH = @"millisecondsSinceEpoch";
NSString *const REPEAT_INTERVAL = @"repeatInterval";
NSString *const REPEAT_TIME = @"repeatTime";
NSString *const HOUR = @"hour";
NSString *const MINUTE = @"minute";
NSString *const SECOND = @"second";
NSString *const SCHEDULED_DATE_TIME = @"scheduledDateTime";
NSString *const TIME_ZONE_NAME = @"timeZoneName";
NSString *const MATCH_DATE_TIME_COMPONENTS = @"matchDateTimeComponents";
NSString *const UILOCALNOTIFICATION_DATE_INTERPRETATION =
@"uiLocalNotificationDateInterpretation";
NSString *const NOTIFICATION_ID = @"NotificationId";
NSString *const PAYLOAD = @"payload";
NSString *const NOTIFICATION_LAUNCHED_APP = @"notificationLaunchedApp";
NSString *const ACTION_ID = @"actionId";
NSString *const NOTIFICATION_RESPONSE_TYPE = @"notificationResponseType";
NSString *const UNSUPPORTED_OS_VERSION_ERROR_CODE = @"unsupported_os_version";
NSString *const GET_ACTIVE_NOTIFICATIONS_ERROR_MESSAGE =
@"iOS version must be 10.0 or newer to use getActiveNotifications";
typedef NS_ENUM(NSInteger, RepeatInterval) {
EveryMinute,
Hourly,
Daily,
Weekly
};
typedef NS_ENUM(NSInteger, DateTimeComponents) {
Time,
DayOfWeekAndTime,
DayOfMonthAndTime,
DateAndTime
};
typedef NS_ENUM(NSInteger, UILocalNotificationDateInterpretation) {
AbsoluteGMTTime,
WallClockTime
};
static FlutterError *getFlutterError(NSError *error) {
return [FlutterError
errorWithCode:[NSString stringWithFormat:@"Error %d", (int)error.code]
message:error.localizedDescription
details:error.domain];
}
+ (void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar> *)registrar {
FlutterMethodChannel *channel =
[FlutterMethodChannel methodChannelWithName:CHANNEL
binaryMessenger:[registrar messenger]];
FlutterLocalNotificationsPlugin *instance =
[[FlutterLocalNotificationsPlugin alloc] initWithChannel:channel
registrar:registrar];
if ([FlutterEngineManager shouldAddAppDelegateToRegistrar:registrar]) {
[registrar addApplicationDelegate:instance];
}
[registrar addMethodCallDelegate:instance channel:channel];
}
+ (void)setPluginRegistrantCallback:(FlutterPluginRegistrantCallback)callback {
registerPlugins = callback;
}
- (instancetype)initWithChannel:(FlutterMethodChannel *)channel
registrar:(NSObject<FlutterPluginRegistrar> *)registrar {
self = [super init];
if (self) {
_channel = channel;
_registrar = registrar;
_flutterEngineManager = [[FlutterEngineManager alloc] init];
}
return self;
}
- (void)handleMethodCall:(FlutterMethodCall *)call
result:(FlutterResult)result {
if ([INITIALIZE_METHOD isEqualToString:call.method]) {
[self initialize:call.arguments result:result];
} else if ([GET_CALLBACK_METHOD isEqualToString:call.method]) {
result([_flutterEngineManager getCallbackHandle]);
} else if ([SHOW_METHOD isEqualToString:call.method]) {
[self show:call.arguments result:result];
} else if ([ZONED_SCHEDULE_METHOD isEqualToString:call.method]) {
[self zonedSchedule:call.arguments result:result];
} else if ([SCHEDULE_METHOD isEqualToString:call.method]) {
[self schedule:call.arguments result:result];
} else if ([PERIODICALLY_SHOW_METHOD isEqualToString:call.method]) {
[self periodicallyShow:call.arguments result:result];
} else if ([SHOW_DAILY_AT_TIME_METHOD isEqualToString:call.method]) {
[self showDailyAtTime:call.arguments result:result];
} else if ([SHOW_WEEKLY_AT_DAY_AND_TIME_METHOD isEqualToString:call.method]) {
[self showWeeklyAtDayAndTime:call.arguments result:result];
} else if ([REQUEST_PERMISSIONS_METHOD isEqualToString:call.method]) {
[self requestPermissions:call.arguments result:result];
} else if ([CANCEL_METHOD isEqualToString:call.method]) {
[self cancel:((NSNumber *)call.arguments) result:result];
} else if ([CANCEL_ALL_METHOD isEqualToString:call.method]) {
[self cancelAll:result];
} else if ([GET_NOTIFICATION_APP_LAUNCH_DETAILS_METHOD
isEqualToString:call.method]) {
NSMutableDictionary *notificationAppLaunchDetails =
[[NSMutableDictionary alloc] init];
notificationAppLaunchDetails[NOTIFICATION_LAUNCHED_APP] =
[NSNumber numberWithBool:_launchingAppFromNotification];
notificationAppLaunchDetails[@"notificationResponse"] =
_launchNotificationResponseDict;
result(notificationAppLaunchDetails);
} else if ([PENDING_NOTIFICATIONS_REQUESTS_METHOD
isEqualToString:call.method]) {
[self pendingNotificationRequests:result];
} else if ([GET_ACTIVE_NOTIFICATIONS_METHOD isEqualToString:call.method]) {
[self getActiveNotifications:result];
} else {
result(FlutterMethodNotImplemented);
}
}
- (void)pendingUserNotificationRequests:(FlutterResult _Nonnull)result
NS_AVAILABLE_IOS(10.0) {
UNUserNotificationCenter *center =
[UNUserNotificationCenter currentNotificationCenter];
[center getPendingNotificationRequestsWithCompletionHandler:^(
NSArray<UNNotificationRequest *> *_Nonnull requests) {
NSMutableArray<NSMutableDictionary<NSString *, NSObject *> *>
*pendingNotificationRequests =
[[NSMutableArray alloc] initWithCapacity:[requests count]];
for (UNNotificationRequest *request in requests) {
NSMutableDictionary *pendingNotificationRequest =
[[NSMutableDictionary alloc] init];
pendingNotificationRequest[ID] =
request.content.userInfo[NOTIFICATION_ID];
if (request.content.title != nil) {
pendingNotificationRequest[TITLE] = request.content.title;
}
if (request.content.body != nil) {
pendingNotificationRequest[BODY] = request.content.body;
}
if (request.content.userInfo[PAYLOAD] != [NSNull null]) {
pendingNotificationRequest[PAYLOAD] = request.content.userInfo[PAYLOAD];
}
[pendingNotificationRequests addObject:pendingNotificationRequest];
}
result(pendingNotificationRequests);
}];
}
- (void)activeUserNotificationRequests:(FlutterResult _Nonnull)result
NS_AVAILABLE_IOS(10.0) {
UNUserNotificationCenter *center =
[UNUserNotificationCenter currentNotificationCenter];
[center getDeliveredNotificationsWithCompletionHandler:^(
NSArray<UNNotification *> *_Nonnull notifications) {
NSMutableArray<NSMutableDictionary<NSString *, NSObject *> *>
*activeNotifications =
[[NSMutableArray alloc] initWithCapacity:[notifications count]];
for (UNNotification *notification in notifications) {
NSMutableDictionary *activeNotification =
[[NSMutableDictionary alloc] init];
activeNotification[ID] =
notification.request.content.userInfo[NOTIFICATION_ID];
if (notification.request.content.title != nil) {
activeNotification[TITLE] = notification.request.content.title;
}
if (notification.request.content.body != nil) {
activeNotification[BODY] = notification.request.content.body;
}
if (notification.request.content.userInfo[PAYLOAD] != [NSNull null]) {
activeNotification[PAYLOAD] =
notification.request.content.userInfo[PAYLOAD];
}
[activeNotifications addObject:activeNotification];
}
result(activeNotifications);
}];
}
- (void)pendingLocalNotificationRequests:(FlutterResult _Nonnull)result {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
NSArray *notifications =
[UIApplication sharedApplication].scheduledLocalNotifications;
NSMutableArray<NSDictionary<NSString *, NSObject *> *>
*pendingNotificationRequests =
[[NSMutableArray alloc] initWithCapacity:[notifications count]];
for (int i = 0; i < [notifications count]; i++) {
UILocalNotification *localNotification = [notifications objectAtIndex:i];
#pragma clang diagnostic pop
NSMutableDictionary *pendingNotificationRequest =
[[NSMutableDictionary alloc] init];
pendingNotificationRequest[ID] =
localNotification.userInfo[NOTIFICATION_ID];
if (localNotification.userInfo[TITLE] != [NSNull null]) {
pendingNotificationRequest[TITLE] = localNotification.userInfo[TITLE];
}
if (localNotification.alertBody) {
pendingNotificationRequest[BODY] = localNotification.alertBody;
}
if (localNotification.userInfo[PAYLOAD] != [NSNull null]) {
pendingNotificationRequest[PAYLOAD] = localNotification.userInfo[PAYLOAD];
}
[pendingNotificationRequests addObject:pendingNotificationRequest];
}
result(pendingNotificationRequests);
}
- (void)pendingNotificationRequests:(FlutterResult _Nonnull)result {
if (@available(iOS 10.0, *)) {
[self pendingUserNotificationRequests:result];
} else {
[self pendingLocalNotificationRequests:result];
}
}
/// Extracts notification categories from [arguments] and configures them as
/// appropriate.
///
/// This code will simply return the `completionHandler` if not running on a
/// compatible iOS version or when no categories were specified in [arguments].
- (void)configureNotificationCategories:(NSDictionary *_Nonnull)arguments
withCompletionHandler:(void (^)(void))completionHandler {
if (@available(iOS 10.0, *)) {
if ([self containsKey:@"notificationCategories" forDictionary:arguments]) {
NSMutableSet<UNNotificationCategory *> *notificationCategories =
[NSMutableSet set];
NSArray *categories = arguments[@"notificationCategories"];
NSMutableArray<NSString *> *foregroundActionIdentifiers =
[[NSMutableArray alloc] init];
for (NSDictionary *category in categories) {
NSMutableArray<UNNotificationAction *> *newActions =
[NSMutableArray array];
NSArray *actions = category[@"actions"];
for (NSDictionary *action in actions) {
NSString *type = action[@"type"];
NSString *identifier = action[@"identifier"];
NSString *title = action[@"title"];
UNNotificationActionOptions options =
[Converters parseNotificationActionOptions:action[@"options"]];
if ((options & UNNotificationActionOptionForeground) != 0) {
[foregroundActionIdentifiers addObject:identifier];
}
if ([type isEqualToString:@"plain"]) {
[newActions
addObject:[UNNotificationAction actionWithIdentifier:identifier
title:title
options:options]];
} else if ([type isEqualToString:@"text"]) {
NSString *buttonTitle = action[@"buttonTitle"];
NSString *placeholder = action[@"placeholder"];
[newActions addObject:[UNTextInputNotificationAction
actionWithIdentifier:identifier
title:title
options:options
textInputButtonTitle:buttonTitle
textInputPlaceholder:placeholder]];
}
}
UNNotificationCategory *notificationCategory = [UNNotificationCategory
categoryWithIdentifier:category[@"identifier"]
actions:newActions
intentIdentifiers:@[]
options:[Converters parseNotificationCategoryOptions:
category[@"options"]]];
[notificationCategories addObject:notificationCategory];
}
if (notificationCategories.count > 0) {
UNUserNotificationCenter *center =
[UNUserNotificationCenter currentNotificationCenter];
[center setNotificationCategories:notificationCategories];
[[NSUserDefaults standardUserDefaults]
setObject:foregroundActionIdentifiers
forKey:FOREGROUND_ACTION_IDENTIFIERS];
completionHandler();
} else {
completionHandler();
}
}
} else {
completionHandler();
}
}
- (void)getActiveNotifications:(FlutterResult _Nonnull)result {
if (@available(iOS 10.0, *)) {
[self activeUserNotificationRequests:result];
} else {
result([FlutterError errorWithCode:UNSUPPORTED_OS_VERSION_ERROR_CODE
message:GET_ACTIVE_NOTIFICATIONS_ERROR_MESSAGE
details:nil]);
}
}
- (void)initialize:(NSDictionary *_Nonnull)arguments
result:(FlutterResult _Nonnull)result {
if ([self containsKey:DEFAULT_PRESENT_ALERT forDictionary:arguments]) {
_displayAlert = [[arguments objectForKey:DEFAULT_PRESENT_ALERT] boolValue];
}
if ([self containsKey:DEFAULT_PRESENT_SOUND forDictionary:arguments]) {
_playSound = [[arguments objectForKey:DEFAULT_PRESENT_SOUND] boolValue];
}
if ([self containsKey:DEFAULT_PRESENT_BADGE forDictionary:arguments]) {
_updateBadge = [[arguments objectForKey:DEFAULT_PRESENT_BADGE] boolValue];
}
bool requestedSoundPermission = false;
bool requestedAlertPermission = false;
bool requestedBadgePermission = false;
bool requestedCriticalPermission = false;
if ([self containsKey:REQUEST_SOUND_PERMISSION forDictionary:arguments]) {
requestedSoundPermission = [arguments[REQUEST_SOUND_PERMISSION] boolValue];
}
if ([self containsKey:REQUEST_ALERT_PERMISSION forDictionary:arguments]) {
requestedAlertPermission = [arguments[REQUEST_ALERT_PERMISSION] boolValue];
}
if ([self containsKey:REQUEST_BADGE_PERMISSION forDictionary:arguments]) {
requestedBadgePermission = [arguments[REQUEST_BADGE_PERMISSION] boolValue];
}
if ([self containsKey:REQUEST_CRITICAL_PERMISSION forDictionary:arguments]) {
requestedCriticalPermission =
[arguments[REQUEST_CRITICAL_PERMISSION] boolValue];
}
if ([self containsKey:@"dispatcher_handle" forDictionary:arguments] &&
[self containsKey:@"callback_handle" forDictionary:arguments]) {
[_flutterEngineManager
registerDispatcherHandle:arguments[@"dispatcher_handle"]
callbackHandle:arguments[@"callback_handle"]];
}
// Configure the notification categories before requesting permissions
[self configureNotificationCategories:arguments
withCompletionHandler:^{
// Once notification categories are set up, the permissions
// request will pick them up properly.
[self requestPermissionsImpl:requestedSoundPermission
alertPermission:requestedAlertPermission
badgePermission:requestedBadgePermission
criticalPermission:requestedCriticalPermission
result:result];
}];
_initialized = true;
}
- (void)requestPermissions:(NSDictionary *_Nonnull)arguments
result:(FlutterResult _Nonnull)result {
bool soundPermission = false;
bool alertPermission = false;
bool badgePermission = false;
bool criticalPermission = false;
if ([self containsKey:SOUND_PERMISSION forDictionary:arguments]) {
soundPermission = [arguments[SOUND_PERMISSION] boolValue];
}
if ([self containsKey:ALERT_PERMISSION forDictionary:arguments]) {
alertPermission = [arguments[ALERT_PERMISSION] boolValue];
}
if ([self containsKey:BADGE_PERMISSION forDictionary:arguments]) {
badgePermission = [arguments[BADGE_PERMISSION] boolValue];
}
if ([self containsKey:CRITICAL_PERMISSION forDictionary:arguments]) {
criticalPermission = [arguments[CRITICAL_PERMISSION] boolValue];
}
[self requestPermissionsImpl:soundPermission
alertPermission:alertPermission
badgePermission:badgePermission
criticalPermission:criticalPermission
result:result];
}
- (void)requestPermissionsImpl:(bool)soundPermission
alertPermission:(bool)alertPermission
badgePermission:(bool)badgePermission
criticalPermission:(bool)criticalPermission
result:(FlutterResult _Nonnull)result {
if (!soundPermission && !alertPermission && !badgePermission &&
!criticalPermission) {
result(@NO);
return;
}
if (@available(iOS 10.0, *)) {
UNUserNotificationCenter *center =
[UNUserNotificationCenter currentNotificationCenter];
UNAuthorizationOptions authorizationOptions = 0;
if (soundPermission) {
authorizationOptions += UNAuthorizationOptionSound;
}
if (alertPermission) {
authorizationOptions += UNAuthorizationOptionAlert;
}
if (badgePermission) {
authorizationOptions += UNAuthorizationOptionBadge;
}
if (@available(iOS 12.0, *)) {
if (criticalPermission) {
authorizationOptions += UNAuthorizationOptionCriticalAlert;
}
}
[center requestAuthorizationWithOptions:(authorizationOptions)
completionHandler:^(BOOL granted,
NSError *_Nullable error) {
result(@(granted));
}];
} else {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
UIUserNotificationType notificationTypes = 0;
if (soundPermission) {
notificationTypes |= UIUserNotificationTypeSound;
}
if (alertPermission) {
notificationTypes |= UIUserNotificationTypeAlert;
}
if (badgePermission) {
notificationTypes |= UIUserNotificationTypeBadge;
}
UIUserNotificationSettings *settings =
[UIUserNotificationSettings settingsForTypes:notificationTypes
categories:nil];
[[UIApplication sharedApplication]
registerUserNotificationSettings:settings];
#pragma clang diagnostic pop
result(@YES);
}
}
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
- (UILocalNotification *)buildStandardUILocalNotification:
(NSDictionary *)arguments {
UILocalNotification *notification = [[UILocalNotification alloc] init];
#pragma clang diagnostic pop
if ([self containsKey:BODY forDictionary:arguments]) {
notification.alertBody = arguments[BODY];
}
NSString *title;
if ([self containsKey:TITLE forDictionary:arguments]) {
title = arguments[TITLE];
if (@available(iOS 8.2, *)) {
notification.alertTitle = title;
}
}
bool presentAlert = _displayAlert;
bool presentSound = _playSound;
bool presentBadge = _updateBadge;
if (arguments[PLATFORM_SPECIFICS] != [NSNull null]) {
NSDictionary *platformSpecifics = arguments[PLATFORM_SPECIFICS];
if ([self containsKey:PRESENT_ALERT forDictionary:platformSpecifics]) {
presentAlert = [[platformSpecifics objectForKey:PRESENT_ALERT] boolValue];
}
if ([self containsKey:PRESENT_SOUND forDictionary:platformSpecifics]) {
presentSound = [[platformSpecifics objectForKey:PRESENT_SOUND] boolValue];
}
if ([self containsKey:PRESENT_BADGE forDictionary:platformSpecifics]) {
presentBadge = [[platformSpecifics objectForKey:PRESENT_BADGE] boolValue];
}
if ([self containsKey:BADGE_NUMBER forDictionary:platformSpecifics]) {
notification.applicationIconBadgeNumber =
[platformSpecifics[BADGE_NUMBER] integerValue];
}
if ([self containsKey:SOUND forDictionary:platformSpecifics]) {
notification.soundName = [platformSpecifics[SOUND] stringValue];
}
}
if (presentSound && notification.soundName == nil) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
notification.soundName = UILocalNotificationDefaultSoundName;
#pragma clang diagnostic pop
}
notification.userInfo = [self buildUserDict:arguments[ID]
title:title
presentAlert:presentAlert
presentSound:presentSound
presentBadge:presentBadge
payload:arguments[PAYLOAD]];
return notification;
}
- (NSString *)getIdentifier:(id)arguments {
return [arguments[ID] stringValue];
}
- (void)show:(NSDictionary *_Nonnull)arguments
result:(FlutterResult _Nonnull)result {
if (@available(iOS 10.0, *)) {
UNMutableNotificationContent *content =
[self buildStandardNotificationContent:arguments result:result];
[self addNotificationRequest:[self getIdentifier:arguments]
content:content
result:result
trigger:nil];
} else {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
UILocalNotification *notification =
[self buildStandardUILocalNotification:arguments];
[[UIApplication sharedApplication]
presentLocalNotificationNow:notification];
#pragma clang diagnostic pop
result(nil);
}
}
- (void)zonedSchedule:(NSDictionary *_Nonnull)arguments
result:(FlutterResult _Nonnull)result {
if (@available(iOS 10.0, *)) {
UNMutableNotificationContent *content =
[self buildStandardNotificationContent:arguments result:result];
UNCalendarNotificationTrigger *trigger =
[self buildUserNotificationCalendarTrigger:arguments];
[self addNotificationRequest:[self getIdentifier:arguments]
content:content
result:result
trigger:trigger];
} else {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
UILocalNotification *notification =
[self buildStandardUILocalNotification:arguments];
#pragma clang diagnostic pop
NSString *scheduledDateTime = arguments[SCHEDULED_DATE_TIME];
NSString *timeZoneName = arguments[TIME_ZONE_NAME];
NSNumber *matchDateComponents = arguments[MATCH_DATE_TIME_COMPONENTS];
NSNumber *uiLocalNotificationDateInterpretation =
arguments[UILOCALNOTIFICATION_DATE_INTERPRETATION];
NSTimeZone *timezone = [NSTimeZone timeZoneWithName:timeZoneName];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss"];
[dateFormatter setTimeZone:timezone];
NSDate *date = [dateFormatter dateFromString:scheduledDateTime];
notification.fireDate = date;
if (uiLocalNotificationDateInterpretation != nil) {
if ([uiLocalNotificationDateInterpretation integerValue] ==
AbsoluteGMTTime) {
notification.timeZone = nil;
} else if ([uiLocalNotificationDateInterpretation integerValue] ==
WallClockTime) {
notification.timeZone = timezone;
}
}
if (matchDateComponents != nil) {
if ([matchDateComponents integerValue] == Time) {
notification.repeatInterval = NSCalendarUnitDay;
} else if ([matchDateComponents integerValue] == DayOfWeekAndTime) {
notification.repeatInterval = NSCalendarUnitWeekOfYear;
} else if ([matchDateComponents integerValue] == DayOfMonthAndTime) {
notification.repeatInterval = NSCalendarUnitMonth;
} else if ([matchDateComponents integerValue] == DateAndTime) {
notification.repeatInterval = NSCalendarUnitYear;
}
}
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
[[UIApplication sharedApplication] scheduleLocalNotification:notification];
#pragma clang diagnostic pop
result(nil);
}
}
- (void)schedule:(NSDictionary *_Nonnull)arguments
result:(FlutterResult _Nonnull)result {
NSNumber *secondsSinceEpoch =
@([arguments[MILLISECONDS_SINCE_EPOCH] longLongValue] / 1000);
if (@available(iOS 10.0, *)) {
UNMutableNotificationContent *content =
[self buildStandardNotificationContent:arguments result:result];
NSDate *date = [NSDate
dateWithTimeIntervalSince1970:[secondsSinceEpoch longLongValue]];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *dateComponents =
[calendar components:(NSCalendarUnitYear | NSCalendarUnitMonth |
NSCalendarUnitDay | NSCalendarUnitHour |
NSCalendarUnitMinute | NSCalendarUnitSecond)
fromDate:date];
UNCalendarNotificationTrigger *trigger = [UNCalendarNotificationTrigger
triggerWithDateMatchingComponents:dateComponents
repeats:false];
[self addNotificationRequest:[self getIdentifier:arguments]
content:content
result:result
trigger:trigger];
} else {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
UILocalNotification *notification =
[self buildStandardUILocalNotification:arguments];
#pragma clang diagnostic pop
notification.fireDate = [NSDate
dateWithTimeIntervalSince1970:[secondsSinceEpoch longLongValue]];
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
[[UIApplication sharedApplication] scheduleLocalNotification:notification];
#pragma clang diagnostic pop
result(nil);
}
}
- (void)periodicallyShow:(NSDictionary *_Nonnull)arguments
result:(FlutterResult _Nonnull)result {
if (@available(iOS 10.0, *)) {
UNMutableNotificationContent *content =
[self buildStandardNotificationContent:arguments result:result];
UNTimeIntervalNotificationTrigger *trigger =
[self buildUserNotificationTimeIntervalTrigger:arguments];
[self addNotificationRequest:[self getIdentifier:arguments]
content:content
result:result
trigger:trigger];
} else {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
UILocalNotification *notification =
[self buildStandardUILocalNotification:arguments];
#pragma clang diagnostic pop
NSTimeInterval timeInterval = 0;
switch ([arguments[REPEAT_INTERVAL] integerValue]) {
case EveryMinute:
timeInterval = 60;
notification.repeatInterval = NSCalendarUnitMinute;
break;
case Hourly:
timeInterval = 60 * 60;
notification.repeatInterval = NSCalendarUnitHour;
break;
case Daily:
timeInterval = 60 * 60 * 24;
notification.repeatInterval = NSCalendarUnitDay;
break;
case Weekly:
timeInterval = 60 * 60 * 24 * 7;
notification.repeatInterval = NSCalendarUnitWeekOfYear;
break;
}
notification.fireDate = [NSDate dateWithTimeIntervalSinceNow:timeInterval];
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
[[UIApplication sharedApplication] scheduleLocalNotification:notification];
#pragma clang diagnostic pop
result(nil);
}
}
- (void)showDailyAtTime:(NSDictionary *_Nonnull)arguments
result:(FlutterResult _Nonnull)result {
NSDictionary *timeArguments = (NSDictionary *)arguments[REPEAT_TIME];
NSNumber *hourComponent = timeArguments[HOUR];
NSNumber *minutesComponent = timeArguments[MINUTE];
NSNumber *secondsComponent = timeArguments[SECOND];
if (@available(iOS 10.0, *)) {
UNMutableNotificationContent *content =
[self buildStandardNotificationContent:arguments result:result];
NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
[dateComponents setHour:[hourComponent integerValue]];
[dateComponents setMinute:[minutesComponent integerValue]];
[dateComponents setSecond:[secondsComponent integerValue]];
UNCalendarNotificationTrigger *trigger = [UNCalendarNotificationTrigger
triggerWithDateMatchingComponents:dateComponents
repeats:YES];
[self addNotificationRequest:[self getIdentifier:arguments]
content:content
result:result
trigger:trigger];
} else {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
UILocalNotification *notification =
[self buildStandardUILocalNotification:arguments];
#pragma clang diagnostic pop
notification.repeatInterval = NSCalendarUnitDay;
NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
[dateComponents setHour:[hourComponent integerValue]];
[dateComponents setMinute:[minutesComponent integerValue]];
[dateComponents setSecond:[secondsComponent integerValue]];
NSCalendar *calendar = [NSCalendar currentCalendar];
notification.fireDate = [calendar dateFromComponents:dateComponents];
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
[[UIApplication sharedApplication] scheduleLocalNotification:notification];
#pragma clang diagnostic pop
result(nil);
}
}
- (void)showWeeklyAtDayAndTime:(NSDictionary *_Nonnull)arguments
result:(FlutterResult _Nonnull)result {
NSDictionary *timeArguments = (NSDictionary *)arguments[REPEAT_TIME];
NSNumber *dayOfWeekComponent = arguments[DAY];
NSNumber *hourComponent = timeArguments[HOUR];
NSNumber *minutesComponent = timeArguments[MINUTE];
NSNumber *secondsComponent = timeArguments[SECOND];
if (@available(iOS 10.0, *)) {
UNMutableNotificationContent *content =
[self buildStandardNotificationContent:arguments result:result];
NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
[dateComponents setHour:[hourComponent integerValue]];
[dateComponents setMinute:[minutesComponent integerValue]];
[dateComponents setSecond:[secondsComponent integerValue]];
[dateComponents setWeekday:[dayOfWeekComponent integerValue]];
UNCalendarNotificationTrigger *trigger = [UNCalendarNotificationTrigger
triggerWithDateMatchingComponents:dateComponents
repeats:YES];
[self addNotificationRequest:[self getIdentifier:arguments]
content:content
result:result
trigger:trigger];
} else {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
UILocalNotification *notification =
[self buildStandardUILocalNotification:arguments];
#pragma clang diagnostic pop
notification.repeatInterval = NSCalendarUnitWeekOfYear;
NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
[dateComponents setHour:[hourComponent integerValue]];
[dateComponents setMinute:[minutesComponent integerValue]];
[dateComponents setSecond:[secondsComponent integerValue]];
[dateComponents setWeekday:[dayOfWeekComponent integerValue]];
NSCalendar *calendar = [NSCalendar currentCalendar];
notification.fireDate = [calendar dateFromComponents:dateComponents];
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
[[UIApplication sharedApplication] scheduleLocalNotification:notification];
#pragma clang diagnostic pop
result(nil);
}
}
- (void)cancel:(NSNumber *)id result:(FlutterResult _Nonnull)result {
if (@available(iOS 10.0, *)) {
UNUserNotificationCenter *center =
[UNUserNotificationCenter currentNotificationCenter];
NSArray *idsToRemove =
[[NSArray alloc] initWithObjects:[id stringValue], nil];
[center removePendingNotificationRequestsWithIdentifiers:idsToRemove];
[center removeDeliveredNotificationsWithIdentifiers:idsToRemove];
} else {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
NSArray *notifications =
[UIApplication sharedApplication].scheduledLocalNotifications;
#pragma clang diagnostic pop
for (int i = 0; i < [notifications count]; i++) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
UILocalNotification *localNotification = [notifications objectAtIndex:i];
#pragma clang diagnostic pop
NSNumber *userInfoNotificationId =
localNotification.userInfo[NOTIFICATION_ID];
if ([userInfoNotificationId longValue] == [id longValue]) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
[[UIApplication sharedApplication]
cancelLocalNotification:localNotification];
#pragma clang diagnostic pop
break;
}
}
}
result(nil);
}
- (void)cancelAll:(FlutterResult _Nonnull)result {
if (@available(iOS 10.0, *)) {
UNUserNotificationCenter *center =
[UNUserNotificationCenter currentNotificationCenter];
[center removeAllPendingNotificationRequests];
[center removeAllDeliveredNotifications];
} else {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
[[UIApplication sharedApplication] cancelAllLocalNotifications];
#pragma clang diagnostic pop
}
result(nil);
}
- (UNMutableNotificationContent *)
buildStandardNotificationContent:(NSDictionary *)arguments
result:(FlutterResult _Nonnull)result
API_AVAILABLE(ios(10.0)) {
UNMutableNotificationContent *content =
[[UNMutableNotificationContent alloc] init];
if ([self containsKey:TITLE forDictionary:arguments]) {
content.title = arguments[TITLE];
}
if ([self containsKey:BODY forDictionary:arguments]) {
content.body = arguments[BODY];
}
bool presentAlert = _displayAlert;
bool presentSound = _playSound;
bool presentBadge = _updateBadge;
if (arguments[PLATFORM_SPECIFICS] != [NSNull null]) {
NSDictionary *platformSpecifics = arguments[PLATFORM_SPECIFICS];
if ([self containsKey:PRESENT_ALERT forDictionary:platformSpecifics]) {
presentAlert = [[platformSpecifics objectForKey:PRESENT_ALERT] boolValue];
}
if ([self containsKey:PRESENT_SOUND forDictionary:platformSpecifics]) {
presentSound = [[platformSpecifics objectForKey:PRESENT_SOUND] boolValue];
}
if ([self containsKey:PRESENT_BADGE forDictionary:platformSpecifics]) {
presentBadge = [[platformSpecifics objectForKey:PRESENT_BADGE] boolValue];
}
if ([self containsKey:BADGE_NUMBER forDictionary:platformSpecifics]) {
content.badge = [platformSpecifics objectForKey:BADGE_NUMBER];
}
if ([self containsKey:THREAD_IDENTIFIER forDictionary:platformSpecifics]) {
content.threadIdentifier = platformSpecifics[THREAD_IDENTIFIER];
}
if ([self containsKey:ATTACHMENTS forDictionary:platformSpecifics]) {
NSArray<NSDictionary *> *attachments = platformSpecifics[ATTACHMENTS];
if (attachments.count > 0) {
NSMutableArray<UNNotificationAttachment *> *notificationAttachments =
[NSMutableArray arrayWithCapacity:attachments.count];
for (NSDictionary *attachment in attachments) {
NSError *error;
NSMutableDictionary *options = [[NSMutableDictionary alloc] init];
if ([self containsKey:ATTACHMENT_HIDE_THUMBNAIL
forDictionary:attachment]) {
NSNumber *hideThumbnail = attachment[ATTACHMENT_HIDE_THUMBNAIL];
[options
setObject:hideThumbnail
forKey:UNNotificationAttachmentOptionsThumbnailHiddenKey];
}
if ([self containsKey:ATTACHMENT_THUMBNAIL_CLIPPING_RECT
forDictionary:attachment]) {
NSDictionary *thumbnailClippingRect =
attachment[ATTACHMENT_THUMBNAIL_CLIPPING_RECT];
CGRect rect =
CGRectMake([thumbnailClippingRect[@"x"] doubleValue],
[thumbnailClippingRect[@"y"] doubleValue],
[thumbnailClippingRect[@"width"] doubleValue],
[thumbnailClippingRect[@"height"] doubleValue]);
NSDictionary *rectDict =
CFBridgingRelease(CGRectCreateDictionaryRepresentation(rect));
[options
setObject:rectDict
forKey:
UNNotificationAttachmentOptionsThumbnailClippingRectKey];
}
UNNotificationAttachment *notificationAttachment =
[UNNotificationAttachment
attachmentWithIdentifier:attachment[ATTACHMENT_IDENTIFIER]
URL:[NSURL
fileURLWithPath:
attachment
[ATTACHMENT_FILE_PATH]]
options:options
error:&error];
if (error) {
result(getFlutterError(error));
return nil;
}
[notificationAttachments addObject:notificationAttachment];
}
content.attachments = notificationAttachments;
}
}
if ([self containsKey:SOUND forDictionary:platformSpecifics]) {
content.sound = [UNNotificationSound soundNamed:platformSpecifics[SOUND]];
}
if ([self containsKey:SUBTITLE forDictionary:platformSpecifics]) {
content.subtitle = platformSpecifics[SUBTITLE];
}
if (@available(iOS 15.0, *)) {
if ([self containsKey:INTERRUPTION_LEVEL
forDictionary:platformSpecifics]) {
NSNumber *interruptionLevel = platformSpecifics[INTERRUPTION_LEVEL];
if (interruptionLevel != nil) {
content.interruptionLevel = [interruptionLevel integerValue];
}
}
}
if ([self containsKey:@"categoryIdentifier"
forDictionary:platformSpecifics]) {
content.categoryIdentifier = platformSpecifics[@"categoryIdentifier"];
}
}
if (presentSound && content.sound == nil) {
content.sound = UNNotificationSound.defaultSound;
}
content.userInfo = [self buildUserDict:arguments[ID]
title:content.title
presentAlert:presentAlert
presentSound:presentSound
presentBadge:presentBadge
payload:arguments[PAYLOAD]];
return content;
}
- (UNCalendarNotificationTrigger *)buildUserNotificationCalendarTrigger:
(id)arguments NS_AVAILABLE_IOS(10.0) {
NSString *scheduledDateTime = arguments[SCHEDULED_DATE_TIME];
NSString *timeZoneName = arguments[TIME_ZONE_NAME];
NSNumber *matchDateComponents = arguments[MATCH_DATE_TIME_COMPONENTS];