-
Notifications
You must be signed in to change notification settings - Fork 176
Expand file tree
/
Copy pathFirebasePushNotificationManager.cs
More file actions
569 lines (468 loc) · 22.7 KB
/
FirebasePushNotificationManager.cs
File metadata and controls
569 lines (468 loc) · 22.7 KB
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
using Firebase.Analytics;
using Firebase.CloudMessaging;
using Firebase.InstanceID;
using Foundation;
using Plugin.FirebasePushNotification.Abstractions;
using System;
using System.Collections.Generic;
using System.Linq;
using UIKit;
using UserNotifications;
using System.Threading.Tasks;
using Firebase.Core;
namespace Plugin.FirebasePushNotification
{
/// <summary>
/// Implementation for FirebasePushNotification
/// </summary>
public class FirebasePushNotificationManager : NSObject, IFirebasePushNotification, IUNUserNotificationCenterDelegate, IMessagingDelegate
{
public static UNNotificationPresentationOptions CurrentNotificationPresentationOption { get; set; } = UNNotificationPresentationOptions.None;
private static bool EnableDelayedResponse;
static NotificationResponse delayedNotificationResponse = null;
static NSObject messagingConnectionChangeNotificationToken;
static Queue<Tuple<string, bool>> pendingTopics = new Queue<Tuple<string, bool>>();
static bool connected = false;
static NSString FirebaseTopicsKey = new NSString("FirebaseTopics");
const string FirebaseTokenKey = "FirebaseToken";
static NSMutableArray currentTopics = (NSUserDefaults.StandardUserDefaults.ValueForKey(FirebaseTopicsKey) as NSArray ?? new NSArray()).MutableCopy() as NSMutableArray;
public string Token { get { return string.IsNullOrEmpty(Messaging.SharedInstance.FcmToken) ? (NSUserDefaults.StandardUserDefaults.StringForKey(FirebaseTokenKey) ?? string.Empty) : Messaging.SharedInstance.FcmToken; } }
static IList<NotificationUserCategory> usernNotificationCategories = new List<NotificationUserCategory>();
static FirebasePushNotificationTokenEventHandler _onTokenRefresh;
public event FirebasePushNotificationTokenEventHandler OnTokenRefresh
{
add
{
var previous = _onTokenRefresh;
_onTokenRefresh += value;
if (EnableDelayedResponse && previous == null)
{
var token = Token;
if (!string.IsNullOrEmpty(token))
{
_onTokenRefresh?.Invoke(this, new FirebasePushNotificationTokenEventArgs(Token));
}
}
}
remove
{
_onTokenRefresh -= value;
}
}
static FirebasePushNotificationDataEventHandler _onNotificationDeleted;
public event FirebasePushNotificationDataEventHandler OnNotificationDeleted
{
add
{
_onNotificationDeleted += value;
}
remove
{
_onNotificationDeleted -= value;
}
}
static FirebasePushNotificationErrorEventHandler _onNotificationError;
public event FirebasePushNotificationErrorEventHandler OnNotificationError
{
add
{
_onNotificationError += value;
}
remove
{
_onNotificationError -= value;
}
}
static FirebasePushNotificationResponseEventHandler _onNotificationOpened;
public event FirebasePushNotificationResponseEventHandler OnNotificationOpened
{
add
{
var previousVal = _onNotificationOpened;
_onNotificationOpened += value;
if (delayedNotificationResponse != null && previousVal == null)
{
var tmpParams = delayedNotificationResponse;
_onNotificationOpened?.Invoke(CrossFirebasePushNotification.Current, new FirebasePushNotificationResponseEventArgs(tmpParams.Data, tmpParams.Identifier, tmpParams.Type));
delayedNotificationResponse = null;
}
}
remove
{
_onNotificationOpened -= value;
}
}
public NotificationUserCategory[] GetUserNotificationCategories()
{
return usernNotificationCategories?.ToArray();
}
static FirebasePushNotificationDataEventHandler _onNotificationReceived;
public event FirebasePushNotificationDataEventHandler OnNotificationReceived
{
add
{
_onNotificationReceived += value;
}
remove
{
_onNotificationReceived -= value;
}
}
public string[] SubscribedTopics{
get {
//Load all subscribed topics
IList<string> topics = new List<string>();
for (nuint i = 0; i < currentTopics.Count; i++)
{
topics.Add(currentTopics.GetItem<NSString>(i));
}
return topics.ToArray();
}
}
public IPushNotificationHandler NotificationHandler { get; set; }
public static async Task Initialize(NSDictionary options, bool autoRegistration = true, bool enableDelayedResponse = true)
{
EnableDelayedResponse = enableDelayedResponse;
App.Configure();
CrossFirebasePushNotification.Current.NotificationHandler = CrossFirebasePushNotification.Current.NotificationHandler ?? new DefaultPushNotificationHandler();
if (autoRegistration)
{
await CrossFirebasePushNotification.Current.RegisterForPushNotifications();
}
}
public static async void Initialize(NSDictionary options, IPushNotificationHandler pushNotificationHandler, bool autoRegistration = true, bool enableDelayedResponse = true)
{
CrossFirebasePushNotification.Current.NotificationHandler = pushNotificationHandler;
await Initialize(options, autoRegistration);
}
public static async void Initialize(NSDictionary options,NotificationUserCategory[] notificationUserCategories,bool autoRegistration = true, bool enableDelayedResponse = true)
{
await Initialize(options, autoRegistration);
RegisterUserNotificationCategories(notificationUserCategories);
}
public static void RegisterUserNotificationCategories(NotificationUserCategory[] userCategories)
{
if (userCategories != null && userCategories.Length > 0)
{
usernNotificationCategories.Clear();
IList<UNNotificationCategory> categories = new List<UNNotificationCategory>();
foreach (var userCat in userCategories)
{
IList<UNNotificationAction> actions = new List<UNNotificationAction>();
foreach(var action in userCat.Actions)
{
// Create action
var actionID = action.Id;
var title = action.Title;
var notificationActionType = UNNotificationActionOptions.None;
switch (action.Type)
{
case NotificationActionType.AuthenticationRequired:
notificationActionType = UNNotificationActionOptions.AuthenticationRequired;
break;
case NotificationActionType.Destructive:
notificationActionType = UNNotificationActionOptions.Destructive;
break;
case NotificationActionType.Foreground:
notificationActionType = UNNotificationActionOptions.Foreground;
break;
}
var notificationAction = UNNotificationAction.FromIdentifier(actionID, title, notificationActionType);
actions.Add(notificationAction);
}
// Create category
var categoryID = userCat.Category;
var notificationActions = actions.ToArray()?? new UNNotificationAction[]{ };
var intentIDs = new string[] { };
var categoryOptions = new UNNotificationCategoryOptions[] { };
var category = UNNotificationCategory.FromIdentifier(categoryID, notificationActions, intentIDs,userCat.Type == NotificationCategoryType.Dismiss? UNNotificationCategoryOptions.CustomDismissAction:UNNotificationCategoryOptions.None);
categories.Add(category);
usernNotificationCategories.Add(userCat);
}
// Register categories
UNUserNotificationCenter.Current.SetNotificationCategories(new NSSet<UNNotificationCategory>(categories.ToArray()));
}
}
public async Task RegisterForPushNotifications()
{
TaskCompletionSource<bool> permisionTask = new TaskCompletionSource<bool>();
// Register your app for remote notifications.
if (UIDevice.CurrentDevice.CheckSystemVersion(10, 0))
{
// iOS 10 or later
var authOptions = UNAuthorizationOptions.Alert | UNAuthorizationOptions.Badge | UNAuthorizationOptions.Sound;
// For iOS 10 display notification (sent via APNS)
UNUserNotificationCenter.Current.Delegate = CrossFirebasePushNotification.Current as IUNUserNotificationCenterDelegate;
// For iOS 10 data message (sent via FCM)
Messaging.SharedInstance.Delegate = CrossFirebasePushNotification.Current as IMessagingDelegate;
UNUserNotificationCenter.Current.RequestAuthorization(authOptions, (granted, error) =>
{
if (error != null)
_onNotificationError?.Invoke(CrossFirebasePushNotification.Current, new FirebasePushNotificationErrorEventArgs(FirebasePushNotificationErrorType.PermissionDenied, error.Description));
else if (!granted)
_onNotificationError?.Invoke(CrossFirebasePushNotification.Current, new FirebasePushNotificationErrorEventArgs(FirebasePushNotificationErrorType.PermissionDenied, "Push notification permission not granted"));
permisionTask.SetResult(granted);
});
}
else
{
// iOS 9 or before
var allNotificationTypes = UIUserNotificationType.Alert | UIUserNotificationType.Badge | UIUserNotificationType.Sound;
var settings = UIUserNotificationSettings.GetSettingsForTypes(allNotificationTypes, null);
UIApplication.SharedApplication.RegisterUserNotificationSettings(settings);
permisionTask.SetResult(true);
}
var permissonGranted = await permisionTask.Task;
if (permissonGranted)
{
UIApplication.SharedApplication.RegisterForRemoteNotifications();
}
}
public void UnregisterForPushNotifications()
{
if (connected)
{
CrossFirebasePushNotification.Current.UnsubscribeAll();
Disconnect();
}
UIApplication.SharedApplication.UnregisterForRemoteNotifications();
NSUserDefaults.StandardUserDefaults.SetString(string.Empty, FirebaseTokenKey);
InstanceId.SharedInstance.DeleteId((h) => { });
}
/// <summary>
/// Connects to Firebase Cloud Messaging
/// </summary>
public static void Connect()
{
if (messagingConnectionChangeNotificationToken != null)
{
NSNotificationCenter.DefaultCenter.RemoveObserver(messagingConnectionChangeNotificationToken);
}
Messaging.SharedInstance.ShouldEstablishDirectChannel = true;
messagingConnectionChangeNotificationToken = NSNotificationCenter.DefaultCenter.AddObserver(Messaging.ConnectionStateChangedNotification, OnMessagingDirectChannelStateChanged);
}
static void OnMessagingDirectChannelStateChanged(NSNotification notification)
{
if (Messaging.SharedInstance.IsDirectChannelEstablished)
{
connected = true;
while (pendingTopics.Count > 0)
{
var pTopic = pendingTopics.Dequeue();
if (pTopic.Item2)
{
CrossFirebasePushNotification.Current.Subscribe(pTopic.Item1);
}
else
{
CrossFirebasePushNotification.Current.Unsubscribe(pTopic.Item1);
}
}
}
/*else
{
_onNotificationError?.Invoke(CrossFirebasePushNotification.Current, new FirebasePushNotificationErrorEventArgs("Connection couldn't be established"));
}*/
}
public static void Disconnect()
{
// Use this method to release shared resources, save user data, invalidate timers and store the application state.
// If your application supports background exection this method is called instead of WillTerminate when the user quits.
//Messaging.SharedInstance.Disconnect();
Messaging.SharedInstance.ShouldEstablishDirectChannel = false;
connected = false;
if (messagingConnectionChangeNotificationToken != null)
{
NSNotificationCenter.DefaultCenter.RemoveObserver(messagingConnectionChangeNotificationToken);
messagingConnectionChangeNotificationToken = null;
}
}
// To receive notifications in foreground on iOS 10 devices.
[Export("userNotificationCenter:willPresentNotification:withCompletionHandler:")]
public void WillPresentNotification(UNUserNotificationCenter center, UNNotification notification, Action<UNNotificationPresentationOptions> completionHandler)
{
// Do your magic to handle the notification data
System.Console.WriteLine(notification.Request.Content.UserInfo);
System.Diagnostics.Debug.WriteLine("WillPresentNotification");
var parameters = GetParameters(notification.Request.Content.UserInfo);
_onNotificationReceived?.Invoke(CrossFirebasePushNotification.Current, new FirebasePushNotificationDataEventArgs(parameters));
CrossFirebasePushNotification.Current.NotificationHandler?.OnReceived(parameters);
completionHandler(CurrentNotificationPresentationOption);
}
public static void DidReceiveMessage(NSDictionary data)
{
Messaging.SharedInstance.AppDidReceiveMessage(data);
var parameters = GetParameters(data);
_onNotificationReceived?.Invoke(CrossFirebasePushNotification.Current,new FirebasePushNotificationDataEventArgs(parameters));
CrossFirebasePushNotification.Current.NotificationHandler?.OnReceived(parameters);
System.Diagnostics.Debug.WriteLine("DidReceivedMessage");
}
[Obsolete("DidRegisterRemoteNotifications with these parameters is deprecated, please use the other override instead.")]
public static void DidRegisterRemoteNotifications(NSData deviceToken,FirebaseTokenType type)
{
Messaging.SharedInstance.ApnsToken = deviceToken;
}
public static void DidRegisterRemoteNotifications(NSData deviceToken)
{
Messaging.SharedInstance.ApnsToken = deviceToken;
}
public static void RemoteNotificationRegistrationFailed(NSError error)
{
_onNotificationError?.Invoke(CrossFirebasePushNotification.Current, new FirebasePushNotificationErrorEventArgs(FirebasePushNotificationErrorType.RegistrationFailed,error.Description));
}
public void ApplicationReceivedRemoteMessage(RemoteMessage remoteMessage)
{
System.Console.WriteLine(remoteMessage.AppData);
System.Diagnostics.Debug.WriteLine("ApplicationReceivedRemoteMessage");
var parameters = GetParameters(remoteMessage.AppData);
_onNotificationReceived?.Invoke(CrossFirebasePushNotification.Current, new FirebasePushNotificationDataEventArgs(parameters));
CrossFirebasePushNotification.Current.NotificationHandler?.OnReceived(parameters);
}
static IDictionary<string, object> GetParameters(NSDictionary data)
{
var parameters = new Dictionary<string, object>();
var keyAps = new NSString("aps");
var keyAlert = new NSString("alert");
foreach (var val in data)
{
if (val.Key.Equals(keyAps))
{
NSDictionary aps = data.ValueForKey(keyAps) as NSDictionary;
if (aps != null)
{
foreach (var apsVal in aps)
{
if (apsVal.Value is NSDictionary)
{
if (apsVal.Key.Equals(keyAlert))
{
foreach (var alertVal in apsVal.Value as NSDictionary)
{
parameters.Add($"aps.alert.{alertVal.Key}", $"{alertVal.Value}");
}
}
}
else
{
parameters.Add($"aps.{apsVal.Key}", $"{apsVal.Value}");
}
}
}
}
else
{
parameters.Add($"{val.Key}", $"{val.Value}");
}
}
return parameters;
}
public void Subscribe(string[] topics)
{
foreach(var t in topics)
{
Subscribe(t);
}
}
public void Subscribe(string topic)
{
if(!connected)
{
pendingTopics.Enqueue(new Tuple<string,bool>(topic,true));
return;
}
if (!currentTopics.Contains(new NSString(topic)))
{
Messaging.SharedInstance.Subscribe($"/topics/{topic}");
currentTopics.Add(new NSString(topic));
}
NSUserDefaults.StandardUserDefaults.SetValueForKey(currentTopics, FirebaseTopicsKey);
NSUserDefaults.StandardUserDefaults.Synchronize();
}
public void UnsubscribeAll()
{
for (nuint i = 0; i < currentTopics.Count; i++)
{
Unsubscribe(currentTopics.GetItem<NSString>(i));
}
}
public void Unsubscribe(string[] topics)
{
foreach (var t in topics)
{
Unsubscribe(t);
}
}
public void Unsubscribe(string topic)
{
if (!connected)
{
pendingTopics.Enqueue(new Tuple<string, bool>(topic, false));
return;
}
var deletedKey = new NSString($"{topic}");
if (currentTopics.Contains(deletedKey))
{
Messaging.SharedInstance.Unsubscribe($"/topics/{topic}");
nint idx = (nint)currentTopics.IndexOf(deletedKey);
if (idx != -1)
{
currentTopics.RemoveObject(idx);
}
}
NSUserDefaults.StandardUserDefaults.SetValueForKey(currentTopics, FirebaseTopicsKey);
NSUserDefaults.StandardUserDefaults.Synchronize();
}
public void SendDeviceGroupMessage(IDictionary<string, string> parameters, string groupKey, string messageId, int timeOfLive)
{
if (connected)
{
NSMutableDictionary message = new NSMutableDictionary();
foreach (var p in parameters)
{
message.Add(new NSString(p.Key), new NSString(p.Value));
}
Messaging.SharedInstance.SendMessage(message, groupKey, messageId, timeOfLive);
}
}
[Export("userNotificationCenter:didReceiveNotificationResponse:withCompletionHandler:")]
public void DidReceiveNotificationResponse(UNUserNotificationCenter center, UNNotificationResponse response, Action completionHandler)
{
var parameters = GetParameters(response.Notification.Request.Content.UserInfo);
NotificationCategoryType catType = NotificationCategoryType.Default;
if (response.IsCustomAction)
catType = NotificationCategoryType.Custom;
else if (response.IsDismissAction)
catType = NotificationCategoryType.Dismiss;
var notificationResponse = new NotificationResponse(parameters, $"{response.ActionIdentifier}".Equals("com.apple.UNNotificationDefaultActionIdentifier", StringComparison.CurrentCultureIgnoreCase)?string.Empty:$"{response.ActionIdentifier}",catType);
if (EnableDelayedResponse && _onNotificationOpened == null)
{
delayedNotificationResponse = notificationResponse;
}
else
{
_onNotificationOpened?.Invoke(this, new FirebasePushNotificationResponseEventArgs(notificationResponse.Data, notificationResponse.Identifier, notificationResponse.Type));
CrossFirebasePushNotification.Current.NotificationHandler?.OnOpened(notificationResponse);
}
// Inform caller it has been handled
completionHandler();
}
public void DidRefreshRegistrationToken(Messaging messaging, string fcmToken)
{
// Note that this callback will be fired everytime a new token is generated, including the first
// time. So if you need to retrieve the token as soon as it is available this is where that
// should be done.
var refreshedToken = fcmToken;
if (!string.IsNullOrEmpty(refreshedToken))
{
_onTokenRefresh?.Invoke(CrossFirebasePushNotification.Current, new FirebasePushNotificationTokenEventArgs(refreshedToken));
Connect();
}
NSUserDefaults.StandardUserDefaults.SetString(fcmToken, FirebaseTokenKey);
}
}
public enum FirebaseTokenType
{
Sandbox,
Production
}
}