-
Notifications
You must be signed in to change notification settings - Fork 3.9k
/
FLTFirebaseMessagingPlugin.m
1079 lines (940 loc) 路 40.4 KB
/
FLTFirebaseMessagingPlugin.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
// Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#import <TargetConditionals.h>
#import <GoogleUtilities/GULAppDelegateSwizzler.h>
#import <firebase_core/FLTFirebasePluginRegistry.h>
#import <objc/message.h>
#import "FLTFirebaseMessagingPlugin.h"
NSString *const kFLTFirebaseMessagingChannelName = @"plugins.flutter.io/firebase_messaging";
NSString *const kMessagingArgumentCode = @"code";
NSString *const kMessagingArgumentMessage = @"message";
NSString *const kMessagingArgumentAdditionalData = @"additionalData";
NSString *const kMessagingPresentationOptionsUserDefaults =
@"flutter_firebase_messaging_presentation_options";
@implementation FLTFirebaseMessagingPlugin {
FlutterMethodChannel *_channel;
NSObject<FlutterPluginRegistrar> *_registrar;
NSData *_apnsToken;
NSDictionary *_initialNotification;
// Used to track if everything as been initialized before answering
// to the initialNotification request
BOOL _initialNotificationGathered;
FLTFirebaseMethodCallResult *_initialNotificationResult;
NSString *_initialNoticationID;
NSString *_notificationOpenedAppID;
#ifdef __FF_NOTIFICATIONS_SUPPORTED_PLATFORM
API_AVAILABLE(ios(10), macosx(10.14))
__weak id<UNUserNotificationCenterDelegate> _originalNotificationCenterDelegate;
API_AVAILABLE(ios(10), macosx(10.14))
struct {
unsigned int willPresentNotification : 1;
unsigned int didReceiveNotificationResponse : 1;
unsigned int openSettingsForNotification : 1;
} _originalNotificationCenterDelegateRespondsTo;
#endif
}
#pragma mark - FlutterPlugin
- (instancetype)initWithFlutterMethodChannel:(FlutterMethodChannel *)channel
andFlutterPluginRegistrar:(NSObject<FlutterPluginRegistrar> *)registrar {
self = [super init];
if (self) {
_initialNotificationGathered = NO;
_channel = channel;
_registrar = registrar;
// Application
// Dart -> `getInitialNotification`
// ObjC -> Initialize other delegates & observers
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:@selector(application_onDidFinishLaunchingNotification:)
#if TARGET_OS_OSX
name:NSApplicationDidFinishLaunchingNotification
#else
name:UIApplicationDidFinishLaunchingNotification
#endif
object:nil];
}
return self;
}
+ (void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar> *)registrar {
FlutterMethodChannel *channel =
[FlutterMethodChannel methodChannelWithName:kFLTFirebaseMessagingChannelName
binaryMessenger:[registrar messenger]];
id instance = [[FLTFirebaseMessagingPlugin alloc] initWithFlutterMethodChannel:channel
andFlutterPluginRegistrar:registrar];
// Register with internal FlutterFire plugin registry.
[[FLTFirebasePluginRegistry sharedInstance] registerFirebasePlugin:instance];
[registrar addMethodCallDelegate:instance channel:channel];
#if !TARGET_OS_OSX
[registrar publish:instance]; // iOS only supported
#endif
}
- (void)handleMethodCall:(FlutterMethodCall *)call result:(FlutterResult)flutterResult {
FLTFirebaseMethodCallErrorBlock errorBlock = ^(
NSString *_Nullable code, NSString *_Nullable message, NSDictionary *_Nullable details,
NSError *_Nullable error) {
if (code == nil) {
NSDictionary *errorDetails = [self NSDictionaryForNSError:error];
code = errorDetails[kMessagingArgumentCode];
message = errorDetails[kMessagingArgumentMessage];
details = errorDetails;
} else {
details = @{
kMessagingArgumentCode : code,
kMessagingArgumentMessage : message,
};
}
if ([@"unknown" isEqualToString:code]) {
NSLog(@"FLTFirebaseMessaging: An error occurred while calling method %@, errorOrNil => %@",
call.method, [error userInfo]);
}
flutterResult([FLTFirebasePlugin createFlutterErrorFromCode:code
message:message
optionalDetails:details
andOptionalNSError:error]);
};
FLTFirebaseMethodCallResult *methodCallResult =
[FLTFirebaseMethodCallResult createWithSuccess:flutterResult andErrorBlock:errorBlock];
[self ensureAPNSTokenSetting];
if ([@"Messaging#getInitialMessage" isEqualToString:call.method]) {
_initialNotificationResult = methodCallResult;
[self initialNotificationCallback];
} else if ([@"Messaging#deleteToken" isEqualToString:call.method]) {
[self messagingDeleteToken:call.arguments withMethodCallResult:methodCallResult];
} else if ([@"Messaging#getAPNSToken" isEqualToString:call.method]) {
[self messagingGetAPNSToken:call.arguments withMethodCallResult:methodCallResult];
} else if ([@"Messaging#setForegroundNotificationPresentationOptions"
isEqualToString:call.method]) {
[self messagingSetForegroundNotificationPresentationOptions:call.arguments
withMethodCallResult:methodCallResult];
} else if ([@"Messaging#getToken" isEqualToString:call.method]) {
[self messagingGetToken:call.arguments withMethodCallResult:methodCallResult];
} else if ([@"Messaging#getNotificationSettings" isEqualToString:call.method]) {
if (@available(iOS 10, macOS 10.14, *)) {
[self messagingGetNotificationSettings:call.arguments withMethodCallResult:methodCallResult];
} else {
// Defaults handled in Dart.
methodCallResult.success(@{});
}
} else if ([@"Messaging#requestPermission" isEqualToString:call.method]) {
if (@available(iOS 10, macOS 10.14, *)) {
[self messagingRequestPermission:call.arguments withMethodCallResult:methodCallResult];
} else {
// Defaults handled in Dart.
methodCallResult.success(@{});
}
} else if ([@"Messaging#setAutoInitEnabled" isEqualToString:call.method]) {
[self messagingSetAutoInitEnabled:call.arguments withMethodCallResult:methodCallResult];
} else if ([@"Messaging#subscribeToTopic" isEqualToString:call.method]) {
[self messagingSubscribeToTopic:call.arguments withMethodCallResult:methodCallResult];
} else if ([@"Messaging#unsubscribeFromTopic" isEqualToString:call.method]) {
[self messagingUnsubscribeFromTopic:call.arguments withMethodCallResult:methodCallResult];
} else if ([@"Messaging#startBackgroundIsolate" isEqualToString:call.method]) {
methodCallResult.success(nil);
} else {
methodCallResult.success(FlutterMethodNotImplemented);
}
}
- (void)messagingSetForegroundNotificationPresentationOptions:(id)arguments
withMethodCallResult:
(FLTFirebaseMethodCallResult *)result {
NSMutableDictionary *persistedOptions = [NSMutableDictionary dictionary];
if ([arguments[@"alert"] isEqual:@(YES)]) {
persistedOptions[@"alert"] = @YES;
}
if ([arguments[@"badge"] isEqual:@(YES)]) {
persistedOptions[@"badge"] = @YES;
}
if ([arguments[@"sound"] isEqual:@(YES)]) {
persistedOptions[@"sound"] = @YES;
}
[[NSUserDefaults standardUserDefaults] setObject:persistedOptions
forKey:kMessagingPresentationOptionsUserDefaults];
result.success(nil);
}
#pragma mark - Firebase Messaging Delegate
- (void)messaging:(nonnull FIRMessaging *)messaging
didReceiveRegistrationToken:(nullable NSString *)fcmToken {
// Don't crash if the token is reset.
if (fcmToken == nil) {
return;
}
// Send to Dart.
[_channel invokeMethod:@"Messaging#onTokenRefresh" arguments:fcmToken];
// If the users AppDelegate implements messaging:didReceiveRegistrationToken: then call it as well
// so we don't break other libraries.
SEL messaging_didReceiveRegistrationTokenSelector =
NSSelectorFromString(@"messaging:didReceiveRegistrationToken:");
if ([[GULAppDelegateSwizzler sharedApplication].delegate
respondsToSelector:messaging_didReceiveRegistrationTokenSelector]) {
void (*usersDidReceiveRegistrationTokenIMP)(id, SEL, FIRMessaging *, NSString *) =
(typeof(usersDidReceiveRegistrationTokenIMP))&objc_msgSend;
usersDidReceiveRegistrationTokenIMP([GULAppDelegateSwizzler sharedApplication].delegate,
messaging_didReceiveRegistrationTokenSelector, messaging,
fcmToken);
}
}
#pragma mark - NSNotificationCenter Observers
- (void)application_onDidFinishLaunchingNotification:(nonnull NSNotification *)notification {
// Setup UIApplicationDelegate.
#if TARGET_OS_OSX
NSDictionary *remoteNotification = notification.userInfo[NSApplicationLaunchUserNotificationKey];
#else
NSDictionary *remoteNotification =
notification.userInfo[UIApplicationLaunchOptionsRemoteNotificationKey];
#endif
if (remoteNotification != nil) {
// If remoteNotification exists, it is the notification that opened the app.
_initialNotification =
[FLTFirebaseMessagingPlugin remoteMessageUserInfoToDict:remoteNotification];
_initialNoticationID = remoteNotification[@"gcm.message_id"];
}
_initialNotificationGathered = YES;
[self initialNotificationCallback];
#if TARGET_OS_OSX
// For macOS we use swizzling to intercept as addApplicationDelegate does not exist on the macOS
// registrar Flutter implementation.
[GULAppDelegateSwizzler registerAppDelegateInterceptor:self];
[GULAppDelegateSwizzler proxyOriginalDelegateIncludingAPNSMethods];
SEL didReceiveRemoteNotificationWithCompletionSEL =
NSSelectorFromString(@"application:didReceiveRemoteNotification:fetchCompletionHandler:");
if ([[GULAppDelegateSwizzler sharedApplication].delegate
respondsToSelector:didReceiveRemoteNotificationWithCompletionSEL]) {
// noop - user has own implementation of this method in their AppDelegate, this
// means GULAppDelegateSwizzler will have already replaced it with a donor method
} else {
// add our own donor implementation of
// application:didReceiveRemoteNotification:fetchCompletionHandler:
Method donorMethod = class_getInstanceMethod(object_getClass(self),
didReceiveRemoteNotificationWithCompletionSEL);
class_addMethod(object_getClass([GULAppDelegateSwizzler sharedApplication].delegate),
didReceiveRemoteNotificationWithCompletionSEL,
method_getImplementation(donorMethod), method_getTypeEncoding(donorMethod));
}
#else
[_registrar addApplicationDelegate:self];
#endif
// Set UNUserNotificationCenter but preserve original delegate if necessary.
if (@available(iOS 10.0, macOS 10.14, *)) {
BOOL shouldReplaceDelegate = YES;
UNUserNotificationCenter *notificationCenter =
[UNUserNotificationCenter currentNotificationCenter];
if (notificationCenter.delegate != nil) {
#if !TARGET_OS_OSX
// If a UNUserNotificationCenterDelegate is set and it conforms to
// FlutterAppLifeCycleProvider then we don't want to replace it on iOS as the earlier
// call to `[_registrar addApplicationDelegate:self];` will automatically delegate calls
// to this plugin. If we replace it, it will cause a stack overflow as our original
// delegate forwarding handler below causes an infinite loop of forwarding. See
// https://github.com/firebasefire/issues/4026.
if ([notificationCenter.delegate conformsToProtocol:@protocol(FlutterAppLifeCycleProvider)]) {
// Note this one only executes if Firebase swizzling is **enabled**.
shouldReplaceDelegate = NO;
}
#endif
if (shouldReplaceDelegate) {
_originalNotificationCenterDelegate = notificationCenter.delegate;
_originalNotificationCenterDelegateRespondsTo.openSettingsForNotification =
(unsigned int)[_originalNotificationCenterDelegate
respondsToSelector:@selector(userNotificationCenter:openSettingsForNotification:)];
_originalNotificationCenterDelegateRespondsTo.willPresentNotification =
(unsigned int)[_originalNotificationCenterDelegate
respondsToSelector:@selector(userNotificationCenter:
willPresentNotification:withCompletionHandler:)];
_originalNotificationCenterDelegateRespondsTo.didReceiveNotificationResponse =
(unsigned int)[_originalNotificationCenterDelegate
respondsToSelector:@selector(userNotificationCenter:
didReceiveNotificationResponse:withCompletionHandler:)];
}
}
if (shouldReplaceDelegate) {
__strong FLTFirebasePlugin<UNUserNotificationCenterDelegate> *strongSelf = self;
notificationCenter.delegate = strongSelf;
}
}
// We automatically register for remote notifications as
// application:didReceiveRemoteNotification:fetchCompletionHandler: will not get called unless
// registerForRemoteNotifications is called early on during app initialization, calling this from
// Dart would be too late.
#if TARGET_OS_OSX
if (@available(macOS 10.14, *)) {
[[NSApplication sharedApplication] registerForRemoteNotifications];
}
#else
[[UIApplication sharedApplication] registerForRemoteNotifications];
#endif
}
#pragma mark - UNUserNotificationCenter Delegate Methods
#ifdef __FF_NOTIFICATIONS_SUPPORTED_PLATFORM
// Called when a notification is received whilst the app is in the foreground.
- (void)userNotificationCenter:(UNUserNotificationCenter *)center
willPresentNotification:(UNNotification *)notification
withCompletionHandler:
(void (^)(UNNotificationPresentationOptions options))completionHandler
API_AVAILABLE(macos(10.14), ios(10.0)) {
// We only want to handle FCM notifications.
if (notification.request.content.userInfo[@"gcm.message_id"]) {
NSDictionary *notificationDict =
[FLTFirebaseMessagingPlugin NSDictionaryFromUNNotification:notification];
[_channel invokeMethod:@"Messaging#onMessage" arguments:notificationDict];
}
// Forward on to any other delegates amd allow them to control presentation behavior.
if (_originalNotificationCenterDelegate != nil &&
_originalNotificationCenterDelegateRespondsTo.willPresentNotification) {
[_originalNotificationCenterDelegate userNotificationCenter:center
willPresentNotification:notification
withCompletionHandler:completionHandler];
} else {
UNNotificationPresentationOptions presentationOptions = UNNotificationPresentationOptionNone;
NSDictionary *persistedOptions = [[NSUserDefaults standardUserDefaults]
dictionaryForKey:kMessagingPresentationOptionsUserDefaults];
if (persistedOptions != nil) {
if ([persistedOptions[@"alert"] isEqual:@(YES)]) {
presentationOptions |= UNNotificationPresentationOptionAlert;
}
if ([persistedOptions[@"badge"] isEqual:@(YES)]) {
presentationOptions |= UNNotificationPresentationOptionBadge;
}
if ([persistedOptions[@"sound"] isEqual:@(YES)]) {
presentationOptions |= UNNotificationPresentationOptionSound;
}
}
completionHandler(presentationOptions);
}
}
// Called when a user interacts with a notification.
- (void)userNotificationCenter:(UNUserNotificationCenter *)center
didReceiveNotificationResponse:(UNNotificationResponse *)response
withCompletionHandler:(void (^)(void))completionHandler
API_AVAILABLE(macos(10.14), ios(10.0)) {
NSDictionary *remoteNotification = response.notification.request.content.userInfo;
_notificationOpenedAppID = remoteNotification[@"gcm.message_id"];
// We only want to handle FCM notifications and stop firing `onMessageOpenedApp()` when app is
// coming from a terminated state.
if (_notificationOpenedAppID != nil &&
![_initialNoticationID isEqualToString:_notificationOpenedAppID]) {
NSDictionary *notificationDict =
[FLTFirebaseMessagingPlugin remoteMessageUserInfoToDict:remoteNotification];
[_channel invokeMethod:@"Messaging#onMessageOpenedApp" arguments:notificationDict];
}
// Forward on to any other delegates.
if (_originalNotificationCenterDelegate != nil &&
_originalNotificationCenterDelegateRespondsTo.didReceiveNotificationResponse) {
[_originalNotificationCenterDelegate userNotificationCenter:center
didReceiveNotificationResponse:response
withCompletionHandler:completionHandler];
} else {
completionHandler();
}
}
// We don't use this for FlutterFire, but for the purpose of forwarding to any original delegates we
// implement this.
- (void)userNotificationCenter:(UNUserNotificationCenter *)center
openSettingsForNotification:(nullable UNNotification *)notification
API_AVAILABLE(macos(10.14), ios(10.0)) {
// Forward on to any other delegates.
if (_originalNotificationCenterDelegate != nil &&
_originalNotificationCenterDelegateRespondsTo.openSettingsForNotification) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunguarded-availability-new"
[_originalNotificationCenterDelegate userNotificationCenter:center
openSettingsForNotification:notification];
#pragma clang diagnostic pop
}
}
#endif
#pragma mark - AppDelegate Methods
#if TARGET_OS_OSX
// Called when `registerForRemoteNotifications` completes successfully.
- (void)application:(NSApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
#else
- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
#endif
if ([FIRMessaging messaging] == nil) {
_apnsToken = deviceToken;
}
#ifdef DEBUG
[[FIRMessaging messaging] setAPNSToken:deviceToken type:FIRMessagingAPNSTokenTypeSandbox];
#else
[[FIRMessaging messaging] setAPNSToken:deviceToken type:FIRMessagingAPNSTokenTypeProd];
#endif
}
#if TARGET_OS_OSX
// Called when `registerForRemoteNotifications` fails to complete.
- (void)application:(NSApplication *)application
didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
#else
- (void)application:(UIApplication *)application
didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
#endif
NSLog(@"%@", error.localizedDescription);
}
// Called when a remote notification is received via APNs.
#if TARGET_OS_OSX
- (void)application:(NSApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo {
// Only handle notifications from FCM.
if (userInfo[@"gcm.message_id"]) {
NSDictionary *notificationDict =
[FLTFirebaseMessagingPlugin remoteMessageUserInfoToDict:userInfo];
if ([NSApplication sharedApplication].isActive) {
[_channel invokeMethod:@"Messaging#onMessage" arguments:notificationDict];
} else {
[_channel invokeMethod:@"Messaging#onBackgroundMessage" arguments:notificationDict];
}
}
}
#endif
#if !TARGET_OS_OSX
// Called for silent messages (i.e. data only) in the foreground & background
- (BOOL)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo
fetchCompletionHandler:(void (^)(UIBackgroundFetchResult result))completionHandler {
#if __has_include(<FirebaseAuth/FirebaseAuth.h>)
if ([[FIRAuth auth] canHandleNotification:userInfo]) {
completionHandler(UIBackgroundFetchResultNoData);
return YES;
}
#endif
NSDictionary *notificationDict =
[FLTFirebaseMessagingPlugin remoteMessageUserInfoToDict:userInfo];
// Only handle notifications from FCM.
if (userInfo[@"gcm.message_id"]) {
if ([UIApplication sharedApplication].applicationState == UIApplicationStateBackground) {
__block BOOL completed = NO;
// If app is in background state, register background task to guarantee async queues aren't
// frozen.
UIBackgroundTaskIdentifier __block backgroundTaskId =
[application beginBackgroundTaskWithExpirationHandler:^{
@synchronized(self) {
if (completed == NO) {
completed = YES;
completionHandler(UIBackgroundFetchResultNewData);
if (backgroundTaskId != UIBackgroundTaskInvalid) {
[application endBackgroundTask:backgroundTaskId];
backgroundTaskId = UIBackgroundTaskInvalid;
}
}
}
}];
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(25 * NSEC_PER_SEC)),
dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
@synchronized(self) {
if (completed == NO) {
completed = YES;
completionHandler(UIBackgroundFetchResultNewData);
if (backgroundTaskId != UIBackgroundTaskInvalid) {
[application endBackgroundTask:backgroundTaskId];
backgroundTaskId = UIBackgroundTaskInvalid;
}
}
}
});
[_channel invokeMethod:@"Messaging#onBackgroundMessage"
arguments:notificationDict
result:^(id _Nullable result) {
@synchronized(self) {
if (completed == NO) {
completed = YES;
completionHandler(UIBackgroundFetchResultNewData);
if (backgroundTaskId != UIBackgroundTaskInvalid) {
[application endBackgroundTask:backgroundTaskId];
backgroundTaskId = UIBackgroundTaskInvalid;
}
}
}
}];
} else {
// If "alert" (i.e. notification) is present in userInfo, this will be called by the other
// "Messaging#onMessage" channel handler
if (userInfo[@"aps"] != nil && userInfo[@"aps"][@"alert"] == nil) {
[_channel invokeMethod:@"Messaging#onMessage" arguments:notificationDict];
}
completionHandler(UIBackgroundFetchResultNoData);
}
return YES;
} // if (userInfo[@"gcm.message_id"])
return NO;
} // didReceiveRemoteNotification
#endif
#pragma mark - Firebase Messaging API
- (void)messagingUnsubscribeFromTopic:(id)arguments
withMethodCallResult:(FLTFirebaseMethodCallResult *)result {
FIRMessaging *messaging = [FIRMessaging messaging];
NSString *topic = arguments[@"topic"];
[messaging unsubscribeFromTopic:topic
completion:^(NSError *error) {
if (error != nil) {
result.error(nil, nil, nil, error);
} else {
result.success(nil);
}
}];
}
- (void)messagingSubscribeToTopic:(id)arguments
withMethodCallResult:(FLTFirebaseMethodCallResult *)result {
FIRMessaging *messaging = [FIRMessaging messaging];
NSString *topic = arguments[@"topic"];
[messaging subscribeToTopic:topic
completion:^(NSError *error) {
if (error != nil) {
result.error(nil, nil, nil, error);
} else {
result.success(nil);
}
}];
}
- (void)messagingSetAutoInitEnabled:(id)arguments
withMethodCallResult:(FLTFirebaseMethodCallResult *)result {
FIRMessaging *messaging = [FIRMessaging messaging];
messaging.autoInitEnabled = [arguments[@"enabled"] boolValue];
result.success(@{
@"isAutoInitEnabled" : @(messaging.isAutoInitEnabled),
});
}
- (void)messagingRequestPermission:(id)arguments
withMethodCallResult:(FLTFirebaseMethodCallResult *)result
API_AVAILABLE(ios(10), macosx(10.14)) {
NSDictionary *permissions = arguments[@"permissions"];
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
UNAuthorizationOptions options = UNAuthorizationOptionNone;
if ([permissions[@"alert"] isEqual:@(YES)]) {
options |= UNAuthorizationOptionAlert;
}
if ([permissions[@"badge"] isEqual:@(YES)]) {
options |= UNAuthorizationOptionBadge;
}
if ([permissions[@"sound"] isEqual:@(YES)]) {
options |= UNAuthorizationOptionSound;
}
if ([permissions[@"provisional"] isEqual:@(YES)]) {
if (@available(iOS 12.0, *)) {
options |= UNAuthorizationOptionProvisional;
}
}
if ([permissions[@"announcement"] isEqual:@(YES)]) {
if (@available(iOS 13.0, *)) {
// TODO not available in iOS9 deployment target - enable once iOS10+ deployment target
// specified in podspec. options |= UNAuthorizationOptionAnnouncement;
}
}
if ([permissions[@"carPlay"] isEqual:@(YES)]) {
options |= UNAuthorizationOptionCarPlay;
}
if ([permissions[@"criticalAlert"] isEqual:@(YES)]) {
if (@available(iOS 12.0, *)) {
options |= UNAuthorizationOptionCriticalAlert;
}
}
id handler = ^(BOOL granted, NSError *_Nullable error) {
if (error != nil) {
result.error(nil, nil, nil, error);
} else {
[center getNotificationSettingsWithCompletionHandler:^(
UNNotificationSettings *_Nonnull settings) {
result.success(
[FLTFirebaseMessagingPlugin NSDictionaryFromUNNotificationSettings:settings]);
}];
}
};
[center requestAuthorizationWithOptions:options completionHandler:handler];
}
- (void)messagingGetNotificationSettings:(id)arguments
withMethodCallResult:(FLTFirebaseMethodCallResult *)result
API_AVAILABLE(ios(10), macos(10.14)) {
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
[center getNotificationSettingsWithCompletionHandler:^(
UNNotificationSettings *_Nonnull settings) {
result.success([FLTFirebaseMessagingPlugin NSDictionaryFromUNNotificationSettings:settings]);
}];
}
- (void)messagingGetToken:(id)arguments withMethodCallResult:(FLTFirebaseMethodCallResult *)result {
FIRMessaging *messaging = [FIRMessaging messaging];
// Keep behaviour consistent with android platform, newly retrieved tokens are streamed via
// onTokenRefresh
bool refreshToken = messaging.FCMToken == nil ? YES : NO;
[messaging tokenWithCompletion:^(NSString *_Nullable token, NSError *_Nullable error) {
if (error != nil) {
result.error(nil, nil, nil, error);
} else {
if (refreshToken) {
[self->_channel invokeMethod:@"Messaging#onTokenRefresh" arguments:token];
}
result.success(@{@"token" : token});
}
}];
}
- (void)messagingGetAPNSToken:(id)arguments
withMethodCallResult:(FLTFirebaseMethodCallResult *)result {
NSData *apnsToken = [FIRMessaging messaging].APNSToken;
if (apnsToken) {
result.success(@{@"token" : [FLTFirebaseMessagingPlugin APNSTokenFromNSData:apnsToken]});
} else {
result.success(@{@"token" : [NSNull null]});
}
}
- (void)messagingDeleteToken:(id)arguments
withMethodCallResult:(FLTFirebaseMethodCallResult *)result {
FIRMessaging *messaging = [FIRMessaging messaging];
[messaging deleteTokenWithCompletion:^(NSError *_Nullable error) {
if (error != nil) {
result.error(nil, nil, nil, error);
} else {
result.success(nil);
}
}];
}
#pragma mark - FLTFirebasePlugin
- (void)didReinitializeFirebaseCore:(void (^)(void))completion {
completion();
}
- (NSDictionary *_Nonnull)pluginConstantsForFIRApp:(FIRApp *)firebase_app {
return @{
@"AUTO_INIT_ENABLED" : @([FIRMessaging messaging].isAutoInitEnabled),
};
}
- (NSString *_Nonnull)firebaseLibraryName {
return LIBRARY_NAME;
}
- (NSString *_Nonnull)firebaseLibraryVersion {
return LIBRARY_VERSION;
}
- (NSString *_Nonnull)flutterChannelName {
return kFLTFirebaseMessagingChannelName;
}
#pragma mark - Utilities
+ (NSDictionary *)NSDictionaryFromUNNotificationSettings:(UNNotificationSettings *_Nonnull)settings
API_AVAILABLE(ios(10), macos(10.14)) {
NSMutableDictionary *settingsDictionary = [NSMutableDictionary dictionary];
// authorizedStatus
NSNumber *authorizedStatus = @-1;
if (settings.authorizationStatus == UNAuthorizationStatusNotDetermined) {
authorizedStatus = @-1;
} else if (settings.authorizationStatus == UNAuthorizationStatusDenied) {
authorizedStatus = @0;
} else if (settings.authorizationStatus == UNAuthorizationStatusAuthorized) {
authorizedStatus = @1;
}
if (@available(iOS 12.0, *)) {
if (settings.authorizationStatus == UNAuthorizationStatusProvisional) {
authorizedStatus = @2;
}
}
NSNumber *timeSensitive = @-1;
if (@available(iOS 15.0, macOS 12.0, *)) {
if (settings.timeSensitiveSetting == UNNotificationSettingDisabled) {
timeSensitive = @0;
}
if (settings.timeSensitiveSetting == UNNotificationSettingEnabled) {
timeSensitive = @1;
}
}
NSNumber *showPreviews = @-1;
if (@available(iOS 11.0, *)) {
if (settings.showPreviewsSetting == UNShowPreviewsSettingNever) {
showPreviews = @0;
} else if (settings.showPreviewsSetting == UNShowPreviewsSettingAlways) {
showPreviews = @1;
} else if (settings.showPreviewsSetting == UNShowPreviewsSettingWhenAuthenticated) {
showPreviews = @2;
}
}
#pragma clang diagnostic push
#pragma ide diagnostic ignored "OCSimplifyInspectionLegacy"
if (@available(iOS 13.0, *)) {
// TODO not available in iOS9 deployment target - enable once iOS10+ deployment target specified
// in podspec. settingsDictionary[@"announcement"] =
// [FLTFirebaseMessagingPlugin NSNumberForUNNotificationSetting:settings.announcementSetting];
settingsDictionary[@"announcement"] = @-1;
} else {
settingsDictionary[@"announcement"] = @-1;
}
#pragma clang diagnostic pop
if (@available(iOS 12.0, *)) {
settingsDictionary[@"criticalAlert"] =
[FLTFirebaseMessagingPlugin NSNumberForUNNotificationSetting:settings.criticalAlertSetting];
} else {
settingsDictionary[@"criticalAlert"] = @-1;
}
settingsDictionary[@"showPreviews"] = showPreviews;
settingsDictionary[@"authorizationStatus"] = authorizedStatus;
settingsDictionary[@"alert"] =
[FLTFirebaseMessagingPlugin NSNumberForUNNotificationSetting:settings.alertSetting];
settingsDictionary[@"badge"] =
[FLTFirebaseMessagingPlugin NSNumberForUNNotificationSetting:settings.badgeSetting];
settingsDictionary[@"sound"] =
[FLTFirebaseMessagingPlugin NSNumberForUNNotificationSetting:settings.soundSetting];
#if TARGET_OS_OSX
settingsDictionary[@"carPlay"] = @-1;
#else
settingsDictionary[@"carPlay"] =
[FLTFirebaseMessagingPlugin NSNumberForUNNotificationSetting:settings.carPlaySetting];
#endif
settingsDictionary[@"lockScreen"] =
[FLTFirebaseMessagingPlugin NSNumberForUNNotificationSetting:settings.lockScreenSetting];
settingsDictionary[@"notificationCenter"] = [FLTFirebaseMessagingPlugin
NSNumberForUNNotificationSetting:settings.notificationCenterSetting];
settingsDictionary[@"timeSensitive"] = timeSensitive;
return settingsDictionary;
}
+ (NSNumber *)NSNumberForUNNotificationSetting:(UNNotificationSetting)setting
API_AVAILABLE(ios(10), macos(10.14)) {
NSNumber *asNumber = @-1;
if (setting == UNNotificationSettingNotSupported) {
asNumber = @-1;
} else if (setting == UNNotificationSettingDisabled) {
asNumber = @0;
} else if (setting == UNNotificationSettingEnabled) {
asNumber = @1;
}
return asNumber;
}
+ (NSString *)APNSTokenFromNSData:(NSData *)tokenData {
const char *data = [tokenData bytes];
NSMutableString *token = [NSMutableString string];
for (NSInteger i = 0; i < tokenData.length; i++) {
[token appendFormat:@"%02.2hhX", data[i]];
}
return [token copy];
}
#if TARGET_OS_OSX
+ (NSDictionary *)NSDictionaryFromUNNotification:(UNNotification *)notification
API_AVAILABLE(macos(10.14)) {
#else
+ (NSDictionary *)NSDictionaryFromUNNotification:(UNNotification *)notification {
#endif
return [self remoteMessageUserInfoToDict:notification.request.content.userInfo];
}
+ (NSDictionary *)remoteMessageUserInfoToDict:(NSDictionary *)userInfo {
NSMutableDictionary *message = [[NSMutableDictionary alloc] init];
NSMutableDictionary *data = [[NSMutableDictionary alloc] init];
NSMutableDictionary *notification = [[NSMutableDictionary alloc] init];
NSMutableDictionary *notificationIOS = [[NSMutableDictionary alloc] init];
// message.data
for (id key in userInfo) {
// message.messageId
if ([key isEqualToString:@"gcm.message_id"] || [key isEqualToString:@"google.message_id"] ||
[key isEqualToString:@"message_id"]) {
message[@"messageId"] = userInfo[key];
continue;
}
// message.messageType
if ([key isEqualToString:@"message_type"]) {
message[@"messageType"] = userInfo[key];
continue;
}
// message.collapseKey
if ([key isEqualToString:@"collapse_key"]) {
message[@"collapseKey"] = userInfo[key];
continue;
}
// message.from
if ([key isEqualToString:@"from"]) {
message[@"from"] = userInfo[key];
continue;
}
// message.sentTime
if ([key isEqualToString:@"google.c.a.ts"]) {
message[@"sentTime"] = userInfo[key];
continue;
}
// message.to
if ([key isEqualToString:@"to"] || [key isEqualToString:@"google.to"]) {
message[@"to"] = userInfo[key];
continue;
}
// build data dict from remaining keys but skip keys that shouldn't be included in data
if ([key isEqualToString:@"aps"] || [key hasPrefix:@"gcm."] || [key hasPrefix:@"google."]) {
continue;
}
// message.apple.imageUrl
if ([key isEqualToString:@"fcm_options"]) {
if (userInfo[key] != nil && userInfo[key][@"image"] != nil) {
notificationIOS[@"imageUrl"] = userInfo[key][@"image"];
}
continue;
}
data[key] = userInfo[key];
}
message[@"data"] = data;
if (userInfo[@"aps"] != nil) {
NSDictionary *apsDict = userInfo[@"aps"];
// message.category
if (apsDict[@"category"] != nil) {
message[@"category"] = apsDict[@"category"];
}
// message.threadId
if (apsDict[@"thread-id"] != nil) {
message[@"threadId"] = apsDict[@"thread-id"];
}
// message.contentAvailable
if (apsDict[@"content-available"] != nil) {
message[@"contentAvailable"] = @([apsDict[@"content-available"] boolValue]);
}
// message.mutableContent
if (apsDict[@"mutable-content"] != nil && [apsDict[@"mutable-content"] intValue] == 1) {
message[@"mutableContent"] = @([apsDict[@"mutable-content"] boolValue]);
}
// message.notification.*
if (apsDict[@"alert"] != nil) {
// can be a string or dictionary
if ([apsDict[@"alert"] isKindOfClass:[NSString class]]) {
// message.notification.title
notification[@"title"] = apsDict[@"alert"];
} else if ([apsDict[@"alert"] isKindOfClass:[NSDictionary class]]) {
NSDictionary *apsAlertDict = apsDict[@"alert"];
// message.notification.title
if (apsAlertDict[@"title"] != nil) {
notification[@"title"] = apsAlertDict[@"title"];
}
// message.notification.titleLocKey
if (apsAlertDict[@"title-loc-key"] != nil) {
notification[@"titleLocKey"] = apsAlertDict[@"title-loc-key"];
}
// message.notification.titleLocArgs
if (apsAlertDict[@"title-loc-args"] != nil) {
notification[@"titleLocArgs"] = apsAlertDict[@"title-loc-args"];
}
// message.notification.body
if (apsAlertDict[@"body"] != nil) {
notification[@"body"] = apsAlertDict[@"body"];
}
// message.notification.bodyLocKey
if (apsAlertDict[@"loc-key"] != nil) {
notification[@"bodyLocKey"] = apsAlertDict[@"loc-key"];
}
// message.notification.bodyLocArgs
if (apsAlertDict[@"loc-args"] != nil) {
notification[@"bodyLocArgs"] = apsAlertDict[@"loc-args"];
}
// Apple only
// message.notification.apple.subtitle
if (apsAlertDict[@"subtitle"] != nil) {
notificationIOS[@"subtitle"] = apsAlertDict[@"subtitle"];
}
// Apple only
// message.notification.apple.subtitleLocKey
if (apsAlertDict[@"subtitle-loc-key"] != nil) {
notificationIOS[@"subtitleLocKey"] = apsAlertDict[@"subtitle-loc-key"];
}
// Apple only
// message.notification.apple.subtitleLocArgs
if (apsAlertDict[@"subtitle-loc-args"] != nil) {
notificationIOS[@"subtitleLocArgs"] = apsAlertDict[@"subtitle-loc-args"];
}
// Apple only
// message.notification.apple.badge
if (apsAlertDict[@"badge"] != nil) {
notificationIOS[@"badge"] = apsAlertDict[@"badge"];
}
}
notification[@"apple"] = notificationIOS;
message[@"notification"] = notification;
}
// message.notification.apple.sound
if (apsDict[@"sound"] != nil) {
if ([apsDict[@"sound"] isKindOfClass:[NSString class]]) {
// message.notification.apple.sound
notification[@"sound"] = @{
@"name" : apsDict[@"sound"],
@"critical" : @NO,
@"volume" : @1,
};
} else if ([apsDict[@"sound"] isKindOfClass:[NSDictionary class]]) {
NSDictionary *apsSoundDict = apsDict[@"sound"];
NSMutableDictionary *notificationIOSSound = [[NSMutableDictionary alloc] init];
// message.notification.apple.sound.name String
if (apsSoundDict[@"name"] != nil) {
notificationIOSSound[@"name"] = apsSoundDict[@"name"];
}
// message.notification.apple.sound.critical Boolean
if (apsSoundDict[@"critical"] != nil) {
notificationIOSSound[@"critical"] = @([apsSoundDict[@"critical"] boolValue]);
}
// message.notification.apple.sound.volume Number
if (apsSoundDict[@"volume"] != nil) {
notificationIOSSound[@"volume"] = apsSoundDict[@"volume"];
}
// message.notification.apple.sound
notificationIOS[@"sound"] = notificationIOSSound;
}
notification[@"apple"] = notificationIOS;
message[@"notification"] = notification;
}
}
return message;
}
- (void)ensureAPNSTokenSetting {
FIRMessaging *messaging = [FIRMessaging messaging];