# @segment/analytics-react-native-plugin-engage

> A plugin for Twilio Segment's Engage push notification service

Latest version **1.1.1** (published 2023-11-07) · MIT license · 0 weekly downloads

## Install

```sh
npm install @segment/analytics-react-native-plugin-engage
pnpm add @segment/analytics-react-native-plugin-engage
yarn add @segment/analytics-react-native-plugin-engage
bun add @segment/analytics-react-native-plugin-engage
```

## Health

**Score 30/100 (F)** — status: abandoned.

Positive: has types; esm support; no vulnerabilities; high quality score.

Warnings: low downloads.

Negative: abandoned; low maintenance score.

## Facts

| | |
|---|---|
| Version | 1.1.1 |
| Published | 2023-11-07 |
| First published | 2023-09-26 |
| Weekly downloads | 0 |
| License | MIT |
| TypeScript types | bundled |
| Module format | ESM + CommonJS |
| Node | >= 18.0.0 |
| Dependencies | 2 |
| Unpacked size | 134.7 KB |
| Known vulnerabilities | 0 |
| Install scripts | no |
| Author | Alan Charles |
| Maintainers | nlubchenco, jamezhutwilio, knksmith57-segment, jsh-wu, nithin-benny, poojasegment, ebru.odok, bannapple, rodhilton_twilio, guthriesegment, srishti-nema, cdelaomartinez, miguelpdiaz8, sundareswar.jayakumar, gbatra, spencerattick, akodankiry, nanette.ranes, gsolis_segment, nitinpm432, aadityabhatt10, amigandhi, segmentsean, hmohanram_seg, jrupasinghe, myrontin.segment, devthale, smccoy-twilio, akurapati-segment, seg-leonelsanches, jibrang, sethgrid_segment, light-bringer-blr, aubreysine, ed-twilion-npm, harsh-joshi99, irfan.ali.segment, kbhargavaram-sg, needcaffeine, nat-grid, spandananune92, wlumsegment, vivek-26, moyara2, bala.singareddy, gbbastos, sprasannasastry22, akash.gautam07, preetyp, viveksainaneesegment, msaraf, kjoerres, rokatyal, ainatancinco, anton-vylushchak, sowjanyasegment, alayvora, pzawadzki, msaunders-segment, tw-dgarcia, bvakkalagadda, mbreske, nsandhu-segment, parag.panda, blangtwilio, ryanrouleau-segment, twjosiah, mcullenmeyer, nina-y, david.anusontarangkul.segment, mckern_segment, segment-admin, nainy.agrawal, tdibacco, sudojatin, nageshgolem, brandonheyer-segment, teganduong, alfrimpong, dobrin.ganev, ankit.gupta.unthinkable, marinhero, benattwilio, bharath.boregowda, conniechen, sungju.jin, pooyaj, yli119, ea_segment, emilyjia, kx-segment, cvillela_segment, xinghao.huang, harsh.vardhan, joe.ayoub.segment, gkochar123, rollcode, ariel.silvestri, cherylj-segment, leifdreizler, immanoj, aaronklish, michelr, maneesh.dharma29, msolorzano-segment, brianhumphreystwilio, jfehrman.segment, joetessy, pmunin, jalexy12, jbandi-twilio, prayansh-twilio, dominicbarnes, brandon.scott-segment, bgillan, phillip.thomas, ricardo.rossi, forgetfulfellow, fauzy.yy, mayur-pitale, dbaik-twilio-segment, seg-rustybailey, tanya.gupta.segment, pmiller-twilio, nevermore2022, aishikawaki, csayuso, mcoulibali, shupadhyay, swgupta, sumit1606, jahood-twilio, saisagarkappaganthula, dostwal, rmukundan, ngoldman-twilio, apareek-twilio, arubiochavez, shuvrajit9904, s3gm3nt, ama0223, tbrennanj, dangmai-segment, shraddha-twilio, taricjain, snehauppalapati, nitish.dubey, azhaotwilio, ryder.wendt, sa-jsooter, enyi.asonye, afsha-nazim-seg, akurapati, mschaszberger, lnamba, varadarajan-tw, seanhan-segment, replatero, sayan-das-in, justeen, sausingh, jgabe13, haeyoon.paik, meg1000, funlu, ashwitha.bg, whaider_twilio, tcgilbert, kevinburkesegment, felttrip, prabhnoor1997, akashyap91, connormarchand, clintz.seg, karimkeshwani, wally.tg, rhall-twilio, yash-twilio, brookstaylorjr, shayan-golafshani, lerahulram, shpankau, mugelstad, hdamani, brchristy, rrivera-segment, sethnutetwilio, fplinke, manali-bhosale, chtoombs, sethsegment, eric-hyde, elmoselyee, michaelghseg, jayakrishnannair, lateefat, maryam.sharif, wdbetts, ryanligon, sindhusegment, lfdelossantos, aramakrishnan, segment-camden, vbatanov, lluque-twilio, jair.aviles, pmaid, song4you, peterdemartini, emmy.byrne, vincen7tran, dean-huynh, cdignam-segment, abhinavsureka, rikezatsegment, arunlalam-segment, cjradek, neeharikakondipati, simpixelated, chihchun-twilio, acharles14, jyim008, seghungtran, hema-segment, oscb, krousseau, sachinwathore, fhalim-segment, cfree, hjoonpm, celine-segment, parsa-segment, pmcanseco-segment, masira, amillet89, cholt002, av-segment, aghotikar, vikrant-segment, larryatsegment, shivpoojan-segment, ariel_segment, scruwys1, lew-gordon, kyliepedersen, jinapark, segmentio, rajulvadera, lpediredla, n2parko, sahilp, tyson_segment, bgamwell, uditmehta, salolivares, erikdw, chenxiangzhang, mericsson, prayansh-segmentt, jeremylarkin, bsneed, danieljackins, segment-seth, james9446, priscilla.giatti, kellylu, nlsun, drew-thompson, segment-jsingh, andrius-segment, valerieernst, khinkalilover, kelcook, gilomer, marcelopv, eric.rogner, kdharaiya, jon.anderson-at-segment.com, stacy.song, niveda.balananthan, rexatsegment, nickaguilar, bradenbecker, reneewang, dan.lasky, sam.tapia, vikramkumar19, mpriyad25, jeremy.parker, smidges |
| Keywords | react-native, ios, android |

## Links

- npm: https://www.npmjs.com/package/@segment/analytics-react-native-plugin-engage
- Repository: https://www.github.com
- Homepage: https://www.github.com#readme
- Issues: https://www.github.com/issues
- npm.io page: https://npm.io/package/@segment/analytics-react-native-plugin-engage

## Dependencies (2)

- [react-native-get-random-values](https://npm.io/package/react-native-get-random-values.md) ^1.9.0
- [@react-native-async-storage/async-storage](https://npm.io/package/@react-native-async-storage/async-storage.md) ^1.15.7

## Alternatives

- [@sindresorhus/slugify](https://npm.io/package/@sindresorhus/slugify.md) — 3.7M weekly downloads
- [solid-js](https://npm.io/package/solid-js.md) — 2.7M weekly downloads
- [expo-glass-effect](https://npm.io/package/expo-glass-effect.md) — 2.5M weekly downloads
- [nanoassert](https://npm.io/package/nanoassert.md) — 780.8K weekly downloads
- [@ffmpeg/ffmpeg](https://npm.io/package/@ffmpeg/ffmpeg.md) — 529.5K weekly downloads

## Recent versions

- 1.1.1 (latest) — 2023-11-07
- 1.1.0 — 2023-09-29
- 1.0.0 — 2023-09-26

## README

# Twilio Engage Plugin

- [Twilio Engage Destination](#twilio-engage-destination)
  - [Getting Started](#getting-started)
  - [Subscription](#subscription)
  - [Additional Setup](#additional-setup)
  - [Predefined Actions](#predefined-actions)
  - [Handling Notifications](#handling-notifications)
  - [Handling Media](#handling-media)
    - [Create Extension](#creating-the-extension)
    - [Display Media](#displaying-media)
  - [License](#license)

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](https://segment.com/docs/connections/sources/catalog/libraries/mobile/react-native/#getting-started) 
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:
```bash
npm install --save @segment/analytics-react-native-plugin-engage @react-native-firebase/app @react-native-firebase/messaging
```

Using Yarn:
```bash
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](https://rnfirebase.io) and [React Native Firebase Messaging](https://rnfirebase.io/analytics/usage) for more details of Firebase packages.

## Usage

Follow the [instructions for adding plugins](https://github.com/segmentio/analytics-react-native#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. 

```ts
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**

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


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

```
**AppDelegate.mm**

```objc
#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`: 

```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

```objc

- (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](https://developer.apple.com/documentation/usernotifications/unnotificationserviceextension).

### Creating the Extension 

1. in Xcode, go to File -> New -> Target
<img width="561" alt="image" src="https://github.com/segment-integrations/analytics-swift-engage/assets/50601149/a95db4c4-dc21-4033-89a8-b88cf9cbbd2b">

2. search for the `Notification Service Extension`
<img width="715" alt="image" src="https://github.com/segment-integrations/analytics-swift-engage/assets/50601149/8d23555a-4431-4715-877b-52778e8e489d">

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**

```swift
    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

- [Twilio Engage Destination](#twilio-engage-destination)
  - [Getting Started](#getting-started)
  - [Subscription](#subscription)
  - [Additional Setup](#additional-setup)
  - [Predefined Actions](#predefined-actions)
  - [Handling Notifications](#handling-notifications)
  - [Handling Media](#handling-media)
    - [Create Extension](#creating-the-extension)
    - [Display Media](#displaying-media)
  - [License](#license)

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](https://segment.com/docs/connections/sources/catalog/libraries/mobile/react-native/#getting-started) 
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:
```bash
npm install --save @segment/analytics-react-native-plugin-engage @react-native-firebase/app @react-native-firebase/messaging
```

Using Yarn:
```bash
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](https://rnfirebase.io) and [React Native Firebase Messaging](https://rnfirebase.io/analytics/usage) for more details of Firebase packages.

## Usage

Follow the [instructions for adding plugins](https://github.com/segmentio/analytics-react-native#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. 

```ts
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**

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


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

```
**AppDelegate.mm**

```objc
#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`: 

```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

```objc

- (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](https://developer.apple.com/documentation/usernotifications/unnotificationserviceextension).

### Creating the Extension 

1. in Xcode, go to File -> New -> Target
<img width="561" alt="image" src="https://github.com/segment-integrations/analytics-swift-engage/assets/50601149/a95db4c4-dc21-4033-89a8-b88cf9cbbd2b">

2. search for the `Notification Service Extension`
<img width="715" alt="image" src="https://github.com/segment-integrations/analytics-swift-engage/assets/50601149/8d23555a-4431-4715-877b-52778e8e489d">

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**

```swift
    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.
```

---
_Source: https://npm.io/package/@segment/analytics-react-native-plugin-engage · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
