GithubHelp home page GithubHelp logo

isabella232 / vibes-react-native Goto Github PK

View Code? Open in Web Editor NEW

This project forked from vibes/vibes-react-native

0.0 0.0 0.0 939 KB

React Native plugin for the Vibes SDK

License: MIT License

Shell 0.18% JavaScript 1.74% Ruby 4.15% Objective-C 14.14% Java 37.20% TypeScript 13.13% Swift 29.46%

vibes-react-native's Introduction

vibes-react-native

push sdk

Installation

npm install vibes-react-native

Usage

import Vibes from 'vibes-react-native';

Setup

Android

In the android/build.gradle file of your react-native project, make the following entry in the allprojects> repositories section.

allprojects {
  repositories {
    ....
    maven { url "https://raw.githubusercontent.com/vibes/android-sdk-repository/releases/"}
  }
}

You will need values for vibesAppId and vibesApiUrl in the android/app/build.gradle file of your react-native project as shown below.

defaultConfig {
  ...
  manifestPlaceholders = [vibesAppId: "YOUR_VIBES_APPID"),
                          vibesApiUrl: "VIBES_API_URL"]
}

iOS

In the Info.plist file of your react-native project, make the following entries: VibesAppId and VibesApiURL.

<key>VibesAppId</key>
<string>&lt;your vibes app id&gt;</string>
<key>VibesApiURL</key>
<string>&lt;your vibes api url&gt;</string>

The vibesAppId is Vibes AppID supplied to you by the Vibes Team. For the value of vibesApiUrl, choose one of the following.

Push Notifications Usage

With the supplied credentials, the plugin initializes itself and calls Vibes.registerDevice and Vibes.registerPush when a Firebase token or APNS token is available within the app. This should be enough to start receiving push notifications. However, these additional functions can be called within your application's own lifecycle after the initialization process.

registerDevice

This call registers the device with the Vibes environment, returning a promise that either contains a unique device_id that stays with the app until it is uninstalled, or an error message if registration fails. This is invoked automatically at startup, and is not required unless you desire to do so. Calling it multiple times has no negative effect.

unregisterDevice

This call unregisters the device with the Vibes environment, as well as stops a device from receiving a push notification. It also disables any data collection or reporting functionality on this device. This call returns a promise, which on success contains no data and on failure contains an error message. To recover from this you need to invoke both Vibes.registerDevice and Vibes.registerPush.

registerPush

This call fetches the platform specific token for the device and submits it to the Vibes environment, which it can then use to target this device. This call returns a promise, which on success contains no data and on failure contains an error message.

For Android, this is invoked automatically at startup of application, and is not required unless you desire to do so.

For iOS, you will need to manually call Vibes.registerPush() from the lifecycle point of entry of your landing page inside your react-native project. This should show push notifications permissions alert dialog, which once granted, will trigger registerPush call on the Vibes SDK with the APNS push token.

unregisterPush

This call notifies the Vibes environment not to send any more push notifications to this device. This call returns a promise, which on success contains no data and on failure contains an error message.

getVibesDeviceInfo

This call returns a json payload containing the device_id and push_token which identifies an installed instance of the app. This call returns a promise with the json payload on success and on failure contains an error message. The payload looks like below.

{
    'device_id': 'vXJ6f67XfnH/OYWskzUakSczrQ8=',
    'push_token': 'eAY6g9q3raJ4P03wNdSWC5MOW1EfxoomWNXsPhi7T6Q9yAqmxqn0sLEUjLL1Ib0LCH3nKQWBXdxapQ5LgbHu+g==',
}

Push notification callbacks

Your react-native application can register to be notified of the json payload associated with 2 types of events.

  • pushReceived - this is raised immediately a push notification is received.
  • pushOpened - this is raised when a user of your app interacts with the received notification by tapping on it.

An example of how to subscribe to these 2 events is shown below.

const onPushReceived = (event: { payload: string }) => {
  alert('Push received. Payload -> ' + JSON.stringify(event.payload));
};

const onPushOpened = async (event: { payload: string }) => {
  // eslint-disable-next-line no-alert
  alert('Push opened. Payload -> ' + JSON.stringify(event.payload));
};

const eventEmitter =
  Platform.OS === 'ios'
    ? new NativeEventEmitter(NativeModules.PushEventEmitter)
    : DeviceEventEmitter;

eventEmitter.addListener('pushReceived', onPushReceived);
eventEmitter.addListener('pushOpened', onPushOpened);


const App = (): React.ReactElement => {
  ...
}
...

The json payload may look like below for an Android app

{  
   "message_uid":"d4799f7e-442e-45e6-a2d7-e7a82785333a",
   "body":"Test Message",
   "title":"Test Message",
   ...
}

The json payload may look like below for an iOS app

{  
    "aps":{ 
      "alert":{ 
         "title":"Test Message",
         "body":"Test Message",
      },
      "badge":1,
      "content-available":1,
      "mutable-content":1
   }
   ...
}

Associating a User With a Device for Targeting

To link a device to a user, perhaps by their username/email or any other unique identifier, you can use the associatePerson bridge function.

const onPress = () => {
    try {
      const result = await Vibes.associatePerson('[email protected]');
      console.log(result)
    } catch (error) {
      console.error(error);
    }
  };

updateDevice

This call updates client device information with Vibes. It returns a promise, which on success contains no data and on failure contains an error message. The method requires key parameters i.e.

updateCredential of type boolean which indicates whether an update is a token update otherwise false latitude and longitude of type Double

Rich Push Display

Android

  • Push notification icon - The plugin looks for a drawable named ic_stat_vibes_notif_icon.png in the resources section of your project, and uses that to display an icon when push is received.
  • Sound - The plugin looks for sound files in raw folder of the Android resources, and plays them when instructed to do so based on the payload contained in the notification. Note that sound will only play if you pass along a Notification Channel in the push payload else the default VIBES notification channel will be used, which doesn't play sound.

Refer to the sample app included in the sample-app folder in this project to see how these 2 are configured.

Further documentation on customizing the notification icon, notification channels, sound, displaying images in notification and other extras can be found in the Android SDK documentation here

Adding Rich Push for iOS

To Add Rich Push to iOS, you need to add a Service Extenstion to the project. The service extension sits between the APNS server and the final content of the push and gets a limited execution time to perform some logic on the incoming push payload. This allows you to intercept the push content coming in from the APNS, modify it and then deliver the modified payload to the user.

Steps to add:

  1. Go to the iOS project under <your_rn_project>/ios and open the .xcworkspace on XCode.
  2. On XCode create a new target by clicking File ▸ New ▸ Target….
  3. Filter for the Notification Service Extension and click Next: Notification Service Dialog
  4. Give it a name say RichPush, select Team, Bundle ID and language to use (you mostly want to stick with Swift here) and should be set to Embeded in Application(this is your main application project).Then click Finish.
  5. If you wish to expose some of the helper classes to the new services extension you created, select the file you wish to expose, go to File Inspector and add a check to your service extension target. File Inspector Dialog
  6. Next go to your Apple Developer Page and create a Siging Certificate and Provisioning Profile for the Bundle ID you selected above. Make sure these are selected under Signing & Capabilities tab on your XCode project setting. You may also just use Automatic Signing if this suits your needs. Signing & Capabilities
  7. You new RichPush target will have a NotificationService.swift file created wich should allow you to intercept and modify the notification.
import UserNotifications
import MobileCoreServices

@available(iOS 10.0, *)
class NotificationService: UNNotificationServiceExtension {
 let parse = RichPushNotificationParsing()
 
 override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
     // you may add your notification Parser here e.g to intercept and maybe dowload a media as in our case
   parse.didReceive(request, withContentHandler: contentHandler)
 }
 
 override func serviceExtensionTimeWillExpire() {
   parse.serviceExtensionTimeWillExpire()
 }
}
  1. This is how the notification Parser may loook like if you are looking to download image with url specified in client_app_data using the key media_url when posted from the Campaign Manager.
import UIKit
import UserNotifications

class RichPushNotificationParsing: NSObject {
    var contentHandler: ((UNNotificationContent) -> Void)?
    var bestAttemptContent: UNMutableNotificationContent?
    fileprivate let kClientDataKey = "client_app_data"
    fileprivate let kMediaUrlKey = "media_url"
    fileprivate let kRichContentIdentifier = "richContent"
    
    func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
        self.contentHandler = contentHandler
        bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent)
        
        if let bestAttemptContent = bestAttemptContent {
            if let clientData = bestAttemptContent.userInfo[kClientDataKey] as? [String: Any] {
                
                guard let attachmentString = clientData[kMediaUrlKey] as? String else {
                    return
                }

                if let attachmentUrl = URL(string: attachmentString) {
                    let session = URLSession(configuration: URLSessionConfiguration.default)
                    let attachmentDownloadTask = session.downloadTask(with: attachmentUrl, completionHandler: { (location, response, error) in
                        if let location = location {
                            let tmpDirectory = NSTemporaryDirectory()
                            let tmpFile = "file://".appending(tmpDirectory).appending(attachmentUrl.lastPathComponent)
                            let tmpUrl = URL(string: tmpFile)!
                            do {
                                try FileManager.default.moveItem(at: location, to: tmpUrl)
                                if let attachment = try? UNNotificationAttachment(identifier: self.kRichContentIdentifier, url: tmpUrl) {
                                    self.bestAttemptContent?.attachments = [attachment]
                                }
                            } catch {
                                print("An exception was caught while downloading the rich content!")
                            }
                        }
                        // Serve the notification content
                        self.contentHandler!(self.bestAttemptContent!)
                    })
                    attachmentDownloadTask.resume()
                }
            }
        }
    }
    
    func serviceExtensionTimeWillExpire() {
        // Called just before the extension will be terminated by the system.
        // Use this as an opportunity to deliver your "best attempt" at modified content, otherwise the original push payload will be used.
        if let contentHandler = contentHandler, let bestAttemptContent =  bestAttemptContent {
            contentHandler(bestAttemptContent)
        }
    }
}
  1. Compile and Build your project to a device capable of receiving Push notifications on the APNs certificate used for your application project.
  2. You should end up with Rich Push notification, when you send a broadcast that has a media attachment from the Campaign Manager.

More information about setting up your iOS app for Rich Push notifications can be found here

License

MIT

vibes-react-native's People

Contributors

clemwek avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.