XToolkit Push Notifications
Rich implementation of common cases for push-notifications using APNs and Firebase Cloud Messaging.
Install
When you use this component separately from WhiteLabel.
Install-Package Softeq.XToolkit.PushNotifications
Setup
Core
- Add the following WhiteLabel projects to references:
Softeq.XToolkit.PushNotifications
- Add implementation for
IPushNotificationsHandler, do whatever you want in:
HandlePushNotificationReceivedHandlePushNotificationTappedHandleSilentPushNotification
all of these methods receive
PushNotificationModel.
OnPushRegistrationCompletedhas parameters showing if registration was completed in system and on server, you can handle it additionally if neededHandleInvalidPushNotificationallows you to handle errors during notification parsing, it contains an Exception and a raw notification objectOnPushPermissionsRequestCompletedis relevant for iOS platform only and allows you to analyze user reaction to notifications permission request (registration will be performed in any case)
- Use default implementation(
PushTokenStorageServicewhich usesIInternalSettings) or add your own implementation forIPushTokenStorageServicewhich:
- implements
PushTokengetter and setter to store the token in internal settings, for instance - implements storing
IsTokenRegisteredInSystemandIsTokenSavedOnServerflags
- Add implementation for
IRemotePushNotificationsService:
- implement methods to send push token to the server and remove it from server
Register your implementations in
Bootstrapper(IPushNotificationsHandler, IRemotePushNotificationsService), also register an implementation ofILogManagerRegister
PushTokenStorageServiceor your implementation asIPushTokenStorageServiceinBootstrapper; if you use default PushTokenStorageService then also registerIInternalSettingsimplementation (possibly in platform projects)
Optionally
- Add enum for push types and a method to convert string type to enum value
Usage
When you want to subscribe to notifications call
IPushNotificationsServicemethodRegisterForPushNotificationsWhen you want to unsubscribe from notifications call
IPushNotificationsServicemethodUnregisterFromPushNotifications, with true parameter if you want to unsubscribe in system as well (default parameter value is false)When you want to clear notifications in notification center call
IPushNotificationsServicemethodClearAllNotificationsWhen you want to manually set a value for app badge call
SetBadgeNumberwith required value (NOTE: on Android https://github.com/wcoder/ShortcutBadger is used and not all devices are supported)
iOS
- Add the following WhiteLabel projects to references:
Softeq.XToolkit.PushNotificationsSofteq.XToolkit.PushNotifications.iOS
Perform standard setup: Add Provisioning profile with Push Notifications capability and pass APNs certificates to the server-side
Add implementation for
INotificationsPermissionsService:
- you can use default implementation
IosNotificationsPermissionsService - you can override
IosNotificationsPermissionsServiceand provide custom authentication options asRequiredAuthOptions - you can provide your own implementation of
INotificationsPermissionsServicewithRequestNotificationsPermissionsmethod using toolkitPermissionManagerfor instance
- If needed add custom subclass of
IosPushNotificationParserwhere you can:
- specify custom key for additional data part of the notification (stored as a peer for apps) - you will be able to handle it as you wish later, default key is
Data; - specify custom way to obtain string type from notification, without it the type will always be an empty string, to do this you have the whole notification, the aps part and the additional data part
If you want to register some categories for your notifications (with or without actions), add an implementation for
INotificationCategoriesProvider. Default implementationIosNotificationCategoriesProviderdoes not contain any categories but provides helper methods for simplified actions and categories setup so you can override it to set up your categories.Register your implementations in
Bootstrapper(INotificationsPermissionsService, IosPushNotificationParser or your custom subclass as IPushNotificationParser, IosNotificationCategoriesProvider if you do not need to work with categories or your custom subclass if you do need to specify some categories as INotificationCategoriesProvider)Register
IosPushNotificationsServiceasIPushNotificationsServiceinBootstrapperIn your
AppDelegate
- In
FinishedLaunchingmethod callIPushNotificationsServicemethodInitializewithForegroundNotificationOptions.ShowWithBadgevalue if you want to display foreground notifications in system notification center and update badge value from notification as well,ForegroundNotificationOptions.Showvalue if you want to display foreground notifications in system notification center but not to update badge value from notification,ForegroundNotificationOptions.DoNotShowif you do not want to display foreground notifications in system notification center - Override
RegisteredForRemoteNotificationsmethod and callIPushNotificationsServicemethodOnRegisteredForPushNotificationswithdeviceToken.AsString() - Override
FailedToRegisterForRemoteNotificationsmethod and callIPushNotificationsServicemethodOnFailedToRegisterForPushNotificationswitherror.Description - If you want to receive silent push notifications override
DidReceiveRemoteNotification(with completionHandler)method and callIPushNotificationsServicemethodOnMessageReceivedwithuserInfoand any value as second parameter. Do not forget to invoke completionHandler. (Make sure thatapsin notification payload containscontent-available:1and does not containalert,soundorbadgekeys)
- Additionally if needed (for silent push notifications) you can add to your
Info.plistUIBackgroundModesremote-notification
Android
- Add the following WhiteLabel projects to references:
Softeq.XToolkit.PushNotificationsSofteq.XToolkit.PushNotifications.Droid
- Perform standard Firebase setup
- Create application project in Firebase Console and pass Server Key to the server-side
- Add
Xamarin.Firebase.Messagingto packages - Add
google-services.jsonto root Droid project with Build Action >GoogleServicesJson - Add the following to your AndroidManifet.xml inside
<application>:
<receiver android:name="com.google.firebase.iid.FirebaseInstanceIdInternalReceiver" android:exported="false" />
<receiver android:name="com.google.firebase.iid.FirebaseInstanceIdReceiver" android:exported="true" android:permission="com.google.android.c2dm.permission.SEND">
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<action android:name="com.google.android.c2dm.intent.REGISTRATION" />
<category android:name="${applicationId}" />
</intent-filter>
</receiver>
- Optionally add also the following to specify icon and color:
<meta-data android:name="com.google.firebase.messaging.default_notification_icon" android:resource="@drawable/ic_notification" />
<meta-data android:name="com.google.firebase.messaging.default_notification_color" android:resource="@color/notification_color" />
Add
Mono.Android.Exportto references (required to be able to identify if notifications are received in foreground)Add implementation for
INotificationsSettingsProvider(they will be applied for manually shown notifications - all data 'notifications' and foreground 'notification' notifications):
- Provide a dictionary of Notification Channels ids and names for Android 8+, the importance for each channel id, the default channel id and a method that returns channel id for specific notification
- If needed provide additional configuration for each notification channel before it's registered (for instance, create and set a group) in
ConfigureNotificationChannel - Provide styles for manually shown notifications (return PushNotificationStyles object, where you have to specify NotificationCompat.Style and may customize other properties like an icon, etc.)
- If needed add more customization of notification (like adding actions) in
CustomizeNotificationBuilder - Provide the type of the Activity which will be opened after tapping on the notification that was shown manually and if parent stack needs to be created for it
- Additionally you can use helper methods from
NotificationActionsHelperto work with actions and fromNotificationChannelsHelperif you need to manage channel groups or notification channels that reflect user choices
- If needed add custom subclass of
DroidPushNotificationParserwhere you can:
- specify custom key for additional data part of the notification (stored inside RemoteMessage.Data) - you will be able to handle it as you wish later, default key is Data;
- specify custom keys for title and body if you have them inside RemoteMessage.Data instead of RemoteMessage's Notification part
- specify custom way to obtain string type from notification, without it the type will always be an empty string, you will have to override two methods - one gives you IDictionary which is RemoteMessage.Data, the other gives you Bundle which stores everything that was in RemoteMessage.Data
Register your implementations in
Bootstrapper(INotificationsSettingsProvider, DroidPushNotificationParser or your custom subclass as IPushNotificationParser)Register
DroidPushNotificationsServiceasIPushNotificationsServicein BootstrapperIn your MainApplication in
OnCreatemethod call IPushNotificationsService method Initialize withForegroundNotificationOptions.Showvalue if you want to display foreground notifications in system notification center,ForegroundNotificationOptions.DoNotShowotherwiseIn your starting activity
OnCreatecheck if Intent?.Extras are not null and contain push notifications data (you can check your custom data key for instance) and call IPushNotificationsService methodOnMessageTapped(extras)in this case (might require a delay or passing forward and calling OnMessageTapped later)