1.1.1 • Published 6 months ago

@segment/analytics-react-native-plugin-engage v1.1.1

Weekly downloads
-
License
MIT
Repository
-
Last release
6 months ago

Twilio Engage Plugin

This plugin enables Segment's Analytics SDK to do push notification management with Twilio Engage.

Getting Started

To get started: 1. follow the set up instructions for Analytics Swift here to integrate Segment's Analytics SDK into your app. 2. add the dependency:

Installation

You need to install the @segment/analytics-react-native-plugin-engage and its dependencies: @react-native-firebase/app and @react-native-firebase/messaging

Using NPM:

npm install --save @segment/analytics-react-native-plugin-engage @react-native-firebase/app @react-native-firebase/messaging

Using Yarn:

yarn add @segment/analytics-react-native-plugin-engage @react-native-firebase/app @react-native-firebase/messaging

Run pod install after the installation to autolink the Engage Plugin.

See React Native Firebase and React Native Firebase Messaging for more details of Firebase packages.

Usage

Follow the instructions for adding plugins on the main Analytics client:

In your code where you initialize the analytics client call the .add(plugin) method with an EngagePlugin instance.

import { createClient } from '@segment/analytics-react-native';

import { FirebasePlugin } from '@segment/analytics-react-native-plugin-engage';

const segmentClient = createClient({
  writeKey: 'SEGMENT_KEY'
});

segmentClient.add({ plugin: new EngagePlugin() });

Subscription

On both iOS and android, three different statuses are tracked: Subscribed, DidNotSubscribe, Unsubscribed.

  • Subscribed is reported whenever app user toggles their device settings to allow push notification
  • DidNotSubscribe is reported in fresh start where no status has ever been reported
  • Unsubscribed is reported whenever user toggles their device settings to disable push notification and when the SDK fails to obtain a token from APNS

Additional Setup (iOS)

You will also need to add or modify the following methods in your AppDelegate.mm and AppDelegate.h in order to start receiving and handling push notifications on iOS:

AppDelegate.h

#import <UserNotifications/UserNotifications.h>
#import <UserNotifications/UNUserNotificationCenter.h>


@interface AppDelegate : UIResponder <UIApplicationDelegate, RCTBridgeDelegate, UNUserNotificationCenterDelegate>

AppDelegate.mm

#import <UserNotifications/UNUserNotificationCenter.h>
#import <segment_analytics_react_native_plugin_engage-Swift.h>


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    UNUserNotificationCenter* center = [UNUserNotificationCenter currentNotificationCenter];
  center.delegate = self;
  [center requestAuthorizationWithOptions:(UNAuthorizationOptionAlert + UNAuthorizationOptionSound)
     completionHandler:^(BOOL granted, NSError * _Nullable error) {
    if (granted) {
        // The user granted authorization.
      dispatch_async(dispatch_get_main_queue(), ^{
          [UIApplication sharedApplication].registerForRemoteNotifications;
      });
    } else {
        // The user did not grant authorization.
        // Disable features that require authorization.
      [AnalyticsReactNativePluginEngage failedToRegister];
    }  }];
  
    NSDictionary *remoteNotification = [launchOptions     objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
      if ([remoteNotification isKindOfClass:[NSDictionary class]]) {
        NSDictionary<NSString *, id<NSCoding>> *notification = (NSDictionary<NSString *, id<NSCoding>> *)remoteNotification;
        [AnalyticsReactNativePluginEngage recievedRemoteNotificationFromLaunch: true];
    }
  
    return YES;
}

- (void) applicationWillEnterForeground:(UIApplication *)application {
  [AnalyticsReactNativePluginEngage retrieveNotificationSettings];
}
- (void)registerForRemoteNotifications {
    // Register for remote notifications.
    [UIApplication.sharedApplication registerForRemoteNotifications];
}


- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
  
  [AnalyticsReactNativePluginEngage retrieveDeviceTokenWithDeviceToken: deviceToken];
}

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
{
  [AnalyticsReactNativePluginEngage failedToRegister];
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
  [AnalyticsReactNativePluginEngage recievedRemoteNotificationFromLaunch: true];
  completionHandler(UIBackgroundFetchResultNoData);
}
- (void)userNotificationCenter:(UNUserNotificationCenter *)center
  didReceiveNotificationResponse:(UNNotificationResponse *)response
         withCompletionHandler:(void (^)(void))completionHandler {
  [AnalyticsReactNativePluginEngage recievedRemoteNotificationFromLaunch: true];

  completionHandler();
}

- (void)userNotificationCenter:(UNUserNotificationCenter *)center
       willPresentNotification:(UNNotification *)notification
         withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler; {
  [AnalyticsReactNativePluginEngage recievedRemoteNotificationFromLaunch: false];
}

Additional Setup (Android)

For the most part, notifications in Android work out of the box. However, you have access to the notification data in your app's MainActivity.java if you would prefer to handle it on your own.

Handling Deep-Links

To open deep-links from a push notification you can do the following in MainActivity.java:

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
  
    if (getIntent().getData() != null) {
      openDeepLink(getIntent().getData());
    }
  }

    private void openDeepLink(Uri data) {
    String scheme = data.getScheme();
    String host = data.getHost();
    String param = data.getQuery();
    Log.d("<TAG>", "Schema: " + scheme);
    Log.d("<TAG>", "Host: " + host);
    Log.d("<TAG>", "Param: " + param);

    //your code to open deep link either in a browser or in a webview
}

Predefined Actions

Twilio Engage provides 4 predefined tapActions that you can handle however you see fit.

  • open_app: the app opens to the main view when the notification/button is on tapped.
  • open_url: the default browser opens a webview to the provided link
  • deep_link: the application routes to the provided link
  • <custom_action>: a custom string which can be handled much like a deep-link depending on the use case.

Handling Notifications (iOS)

How you handle and display notifications is entirely up to you. Examples for each of the predefined tapActions can be found below:

AppDelegate

When a push is received by a device the data is available in didReceiveRemoteNotification (recieved in background) and userNotificationCenter (recieved in foreground) in your AppDelegate

- (void)userNotificationCenter:(UNUserNotificationCenter *)center
  didReceiveNotificationResponse:(UNNotificationResponse *)response
         withCompletionHandler:(void (^)(void))completionHandler {
            NSDictionary *notification = response.notification.request.content.userInfo;
            [self handleNotification:notification shouldAsk:NO];
         }

- (void)userNotificationCenter:(UNUserNotificationCenter *)center
       willPresentNotification:(UNNotification *)notification
         withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler; {
  NSDictionary *userInfo = notification.request.content.userInfo;
  [self handleNotification:userInfo shouldAsk:YES];
  
  [AnalyticsReactNativePluginEngage recievedRemoteNotificationFromLaunch: false];
  
}
 //an example method for handling notifications in your app delegate

 - (void)handleNotification:(NSDictionary *)notification shouldAsk:(BOOL)shouldAsk {
  if ([notification objectForKey:@"aps"]) {
    NSDictionary *aps = [notification objectForKey:@"aps"];
    if ([aps objectForKey:@"category"]) {
      NSString *tapAction = [aps objectForKey:@"category"];
      
      if ([tapAction isEqual:@"open_url"]) {
        if (notification[@"link"] != nil) {
          NSString *urlString = notification[@"link"];
          NSURL *url = [NSURL URLWithString:urlString];
          if (url != nil) {
            //open the default browser with the URL
            [[UIApplication sharedApplication] openURL:url options:nil completionHandler:nil];
          }

        }
      } else if ([tapAction isEqual:@"deep_link"]) {
        // add deepLink view
      } else {
        //this will catch `open_app` to open home screen
        //you can also implement your <custom_action> with
        //another conditional here
        return;
      }
    }
  }
}

Handling Media (iOS)

If you would like to display media in your push notifications, you will need to add a NotificationService extension to your app. Reference Apple's documentation for a more detailed overview of UNNotificationServiceExtension.

Creating the Extension

  1. in Xcode, go to File -> New -> Target

  2. search for the Notification Service Extension

  3. name the extension <YourAppName>NotificationService> and finish the creation process.

  4. <YourAppName>NotificationService/NotificationService> is where you can add custom logic to handle and display media.

Displaying Media

NotificationService didRecieve example

    override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
        self.contentHandler = contentHandler
        bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent)
        
        if let bestAttemptContent = bestAttemptContent {
            var urlString: String? = nil
            let mediaArray: NSArray = bestAttemptContent.userInfo["media"] as! NSArray
            
            if let mediaURLString = mediaArray[0] as? String {
                urlString = mediaURLString
            }
            
            if urlString != nil, let fileURL = URL(string: urlString!){
                
                guard let mediaData = NSData(contentsOf: fileURL) else {
                    contentHandler(bestAttemptContent)
                    return
                }
                
                guard let mediaAttachment = UNNotificationAttachment.saveImageToDisk(fileIdentifier: "engage-image.png", data: mediaData, options: nil) else {
                    contentHandler(bestAttemptContent)
                    return
                }
                
                bestAttemptContent.attachments = [ mediaAttachment ]
            }
            contentHandler(bestAttemptContent)
        }
        
    }

...

//add an extension to `UNNotificationAttachment` to download/save the image 
@available(iOSApplicationExtension 10.0, *)
extension UNNotificationAttachment {
    
    static func saveImageToDisk(fileIdentifier: String, data: NSData, options: [NSObject : AnyObject]?) -> UNNotificationAttachment? {
        let fileManager = FileManager.default
        let folderName = ProcessInfo.processInfo.globallyUniqueString
        let folderURL = NSURL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(folderName, isDirectory: true)
        
        do {
            try fileManager.createDirectory(at: folderURL!, withIntermediateDirectories: true, attributes: nil)
            let fileURL = folderURL?.appendingPathComponent(fileIdentifier)
            try data.write(to: fileURL!, options: [])
            let attachment = try UNNotificationAttachment(identifier: fileIdentifier, url: fileURL!, options: options)
            return attachment
        } catch let error {
            print("error \(error)")
        }
        
        return nil
    }
}

License

MIT License

Copyright (c) 2021 Segment

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

Twilio Engage Plugin

This plugin enables Segment's Analytics SDK to do push notification management with Twilio Engage.

Getting Started

To get started: 1. follow the set up instructions for Analytics Swift here to integrate Segment's Analytics SDK into your app. 2. add the dependency:

Installation

You need to install the @segment/analytics-react-native-plugin-engage and its dependencies: @react-native-firebase/app and @react-native-firebase/messaging

Using NPM:

npm install --save @segment/analytics-react-native-plugin-engage @react-native-firebase/app @react-native-firebase/messaging

Using Yarn:

yarn add @segment/analytics-react-native-plugin-engage @react-native-firebase/app @react-native-firebase/messaging

Run pod install after the installation to autolink the Engage Plugin.

See React Native Firebase and React Native Firebase Messaging for more details of Firebase packages.

Usage

Follow the instructions for adding plugins on the main Analytics client:

In your code where you initialize the analytics client call the .add(plugin) method with an EngagePlugin instance.

import { createClient } from '@segment/analytics-react-native';

import { FirebasePlugin } from '@segment/analytics-react-native-plugin-engage';

const segmentClient = createClient({
  writeKey: 'SEGMENT_KEY'
});

segmentClient.add({ plugin: new EngagePlugin() });

Subscription

On both iOS and android, three different statuses are tracked: Subscribed, DidNotSubscribe, Unsubscribed.

  • Subscribed is reported whenever app user toggles their device settings to allow push notification
  • DidNotSubscribe is reported in fresh start where no status has ever been reported
  • Unsubscribed is reported whenever user toggles their device settings to disable push notification and when the SDK fails to obtain a token from APNS

Additional Setup (iOS)

You will also need to add or modify the following methods in your AppDelegate.mm and AppDelegate.h in order to start receiving and handling push notifications on iOS:

AppDelegate.h

#import <UserNotifications/UserNotifications.h>
#import <UserNotifications/UNUserNotificationCenter.h>


@interface AppDelegate : UIResponder <UIApplicationDelegate, RCTBridgeDelegate, UNUserNotificationCenterDelegate>

AppDelegate.mm

#import <UserNotifications/UNUserNotificationCenter.h>
#import <segment_analytics_react_native_plugin_engage-Swift.h>


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    UNUserNotificationCenter* center = [UNUserNotificationCenter currentNotificationCenter];
  center.delegate = self;
  [center requestAuthorizationWithOptions:(UNAuthorizationOptionAlert + UNAuthorizationOptionSound)
     completionHandler:^(BOOL granted, NSError * _Nullable error) {
    if (granted) {
        // The user granted authorization.
      dispatch_async(dispatch_get_main_queue(), ^{
          [UIApplication sharedApplication].registerForRemoteNotifications;
      });
    } else {
        // The user did not grant authorization.
        // Disable features that require authorization.
      [AnalyticsReactNativePluginEngage failedToRegister];
    }  }];
  
    NSDictionary *remoteNotification = [launchOptions     objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
      if ([remoteNotification isKindOfClass:[NSDictionary class]]) {
        NSDictionary<NSString *, id<NSCoding>> *notification = (NSDictionary<NSString *, id<NSCoding>> *)remoteNotification;
        [AnalyticsReactNativePluginEngage recievedRemoteNotificationFromLaunch: true];
    }
  
    return YES;
}

- (void) applicationWillEnterForeground:(UIApplication *)application {
  [AnalyticsReactNativePluginEngage retrieveNotificationSettings];
}
- (void)registerForRemoteNotifications {
    // Register for remote notifications.
    [UIApplication.sharedApplication registerForRemoteNotifications];
}


- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
  
  [AnalyticsReactNativePluginEngage retrieveDeviceTokenWithDeviceToken: deviceToken];
}

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
{
  [AnalyticsReactNativePluginEngage failedToRegister];
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
  [AnalyticsReactNativePluginEngage recievedRemoteNotificationFromLaunch: true];
  completionHandler(UIBackgroundFetchResultNoData);
}
- (void)userNotificationCenter:(UNUserNotificationCenter *)center
  didReceiveNotificationResponse:(UNNotificationResponse *)response
         withCompletionHandler:(void (^)(void))completionHandler {
  [AnalyticsReactNativePluginEngage recievedRemoteNotificationFromLaunch: true];

  completionHandler();
}

- (void)userNotificationCenter:(UNUserNotificationCenter *)center
       willPresentNotification:(UNNotification *)notification
         withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler; {
  [AnalyticsReactNativePluginEngage recievedRemoteNotificationFromLaunch: false];
}

Additional Setup (Android)

For the most part, notifications in Android work out of the box. However, you have access to the notification data in your app's MainActivity.java if you would prefer to handle it on your own.

Handling Deep-Links

To open deep-links from a push notification you can do the following in MainActivity.java:

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
  
    if (getIntent().getData() != null) {
      openDeepLink(getIntent().getData());
    }
  }

    private void openDeepLink(Uri data) {
    String scheme = data.getScheme();
    String host = data.getHost();
    String param = data.getQuery();
    Log.d("<TAG>", "Schema: " + scheme);
    Log.d("<TAG>", "Host: " + host);
    Log.d("<TAG>", "Param: " + param);

    //your code to open deep link either in a browser or in a webview
}

Predefined Actions

Twilio Engage provides 4 predefined tapActions that you can handle however you see fit.

  • open_app: the app opens to the main view when the notification/button is on tapped.
  • open_url: the default browser opens a webview to the provided link
  • deep_link: the application routes to the provided link
  • <custom_action>: a custom string which can be handled much like a deep-link depending on the use case.

Handling Notifications (iOS)

How you handle and display notifications is entirely up to you. Examples for each of the predefined tapActions can be found below:

AppDelegate

When a push is received by a device the data is available in didReceiveRemoteNotification (recieved in background) and userNotificationCenter (recieved in foreground) in your AppDelegate

- (void)userNotificationCenter:(UNUserNotificationCenter *)center
  didReceiveNotificationResponse:(UNNotificationResponse *)response
         withCompletionHandler:(void (^)(void))completionHandler {
            NSDictionary *notification = response.notification.request.content.userInfo;
            [self handleNotification:notification shouldAsk:NO];
         }

- (void)userNotificationCenter:(UNUserNotificationCenter *)center
       willPresentNotification:(UNNotification *)notification
         withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler; {
  NSDictionary *userInfo = notification.request.content.userInfo;
  [self handleNotification:userInfo shouldAsk:YES];
  
  [AnalyticsReactNativePluginEngage recievedRemoteNotificationFromLaunch: false];
  
}
 //an example method for handling notifications in your app delegate

 - (void)handleNotification:(NSDictionary *)notification shouldAsk:(BOOL)shouldAsk {
  if ([notification objectForKey:@"aps"]) {
    NSDictionary *aps = [notification objectForKey:@"aps"];
    if ([aps objectForKey:@"category"]) {
      NSString *tapAction = [aps objectForKey:@"category"];
      
      if ([tapAction isEqual:@"open_url"]) {
        if (notification[@"link"] != nil) {
          NSString *urlString = notification[@"link"];
          NSURL *url = [NSURL URLWithString:urlString];
          if (url != nil) {
            //open the default browser with the URL
            [[UIApplication sharedApplication] openURL:url options:nil completionHandler:nil];
          }

        }
      } else if ([tapAction isEqual:@"deep_link"]) {
        // add deepLink view
      } else {
        //this will catch `open_app` to open home screen
        //you can also implement your <custom_action> with
        //another conditional here
        return;
      }
    }
  }
}

Handling Media (iOS)

If you would like to display media in your push notifications, you will need to add a NotificationService extension to your app. Reference Apple's documentation for a more detailed overview of UNNotificationServiceExtension.

Creating the Extension

  1. in Xcode, go to File -> New -> Target

  2. search for the Notification Service Extension

  3. name the extension <YourAppName>NotificationService> and finish the creation process.

  4. <YourAppName>NotificationService/NotificationService> is where you can add custom logic to handle and display media.

Displaying Media

NotificationService didRecieve example

    override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
        self.contentHandler = contentHandler
        bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent)
        
        if let bestAttemptContent = bestAttemptContent {
            var urlString: String? = nil
            let mediaArray: NSArray = bestAttemptContent.userInfo["media"] as! NSArray
            
            if let mediaURLString = mediaArray[0] as? String {
                urlString = mediaURLString
            }
            
            if urlString != nil, let fileURL = URL(string: urlString!){
                
                guard let mediaData = NSData(contentsOf: fileURL) else {
                    contentHandler(bestAttemptContent)
                    return
                }
                
                guard let mediaAttachment = UNNotificationAttachment.saveImageToDisk(fileIdentifier: "engage-image.png", data: mediaData, options: nil) else {
                    contentHandler(bestAttemptContent)
                    return
                }
                
                bestAttemptContent.attachments = [ mediaAttachment ]
            }
            contentHandler(bestAttemptContent)
        }
        
    }

...

//add an extension to `UNNotificationAttachment` to download/save the image 
@available(iOSApplicationExtension 10.0, *)
extension UNNotificationAttachment {
    
    static func saveImageToDisk(fileIdentifier: String, data: NSData, options: [NSObject : AnyObject]?) -> UNNotificationAttachment? {
        let fileManager = FileManager.default
        let folderName = ProcessInfo.processInfo.globallyUniqueString
        let folderURL = NSURL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(folderName, isDirectory: true)
        
        do {
            try fileManager.createDirectory(at: folderURL!, withIntermediateDirectories: true, attributes: nil)
            let fileURL = folderURL?.appendingPathComponent(fileIdentifier)
            try data.write(to: fileURL!, options: [])
            let attachment = try UNNotificationAttachment(identifier: fileIdentifier, url: fileURL!, options: options)
            return attachment
        } catch let error {
            print("error \(error)")
        }
        
        return nil
    }
}

License

MIT License

Copyright (c) 2021 Segment

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.