Integration

Capacitors !! lets you build mobile apps using only TypeScript. letting you compose a rich mobile UI from declarative components.

### Install Notifyvisitors Plugin

npm install capacitor-plugin-notifyvisitors

Link Plugin to Project

npx cap sync

Cocoapods Install (IOS Only)

React Native 0.60.0 or higher & Using Cocoapods.

Run this command from terminal

cd ios && pod install && cd ..

SDK Integration (Platfrom Specific)

Android

Configure Icons

For below Lollipop devicesFor Lollipop & above devices
Devices below lollipop shows only one icon in the push notifications, that you can configure from notifyvisitors panel.
To change default notification icon, you can replace icon sm_push.png in yourApp/node_modules/react-native-notifyvisitors/android/src/main/res/drawable folder.
Devices supporting Lollipop & above shows two notifications icons i.e., small push icon & large push icon.

Large push icon: It is configured from panel & is shown as main push icon. However if large push icon is not configured from panel then small push icon is shown as main push icon.
Small push icon: It will be set according to android documentation (https://developer.android.com/about/versions/android-5.0-changes.html). It should be monochrome, otherwise it will be shown as square white spot. The size of monochrome icon will be 200x200 in PNG format.

> Monochrome: Image with One color and transparent background.

📘

Note:

To change default small push icon, you have to replace icon sm_push_logo.png in <yourApp/android/src/main/res/drawable> folder. And also follow below given steps, it is mandatory.

  • To get a small push icon effect in your status-bar:
  1. Go to Android Asset Studio.
  2. Select Notification Icon Generator.
  3. Select Image under Source menu.
    Note: Select here your Monochrome icon.
  4. Copy and paste your small push icon there.
  5. Enter its name in the Name menu on the left side.
    Note: Name here will be as "sm_push_logo".
  6. Download the images from the top-right-corner icon. It will be downloaded as a zip.
  7. Unzip it copy and paste all icons in folders in your app(name-wise).

Configure FCM for Push in Notifyvisitors Panel

  1. If you don’t have your own firebase integration, then

  2. Goto FCM (https://console.firebase.google.com/) and register your app.

  3. Copy Sender Id and Legacy server key from Fcm.

  4. Download the latest config JSON file (google-service.json file) and paste it in your-app folder (yourApp/android/app).

  5. Goto Notifyvisitors panel and from App push menu goto Android inside configuration section from left side menu panel and Paste Sender Id and Legacy server key.

  6. Add the below permission in your app’s build.gradle
    // Add to the bottom of the file

apply plugin: 'com.google.gms.google-services'
  1. Add the below lines Project-level build.gradle (/build.gradle):
buildscript {
  dependencies {
   	 // Add this line
    	classpath 'com.google.gms:google-services:4.0.1'
  }
}

Configure your AndroidManifest.xml

<manifest….>
   <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
   <uses-permission android:name="android.permission.WAKE_LOCK"/>
   <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
   <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
   <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
   <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"/>
   <uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
   <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

<application>

  <meta-data
        android:name="notifyvisitors_bid"
        android:value="5499" />
  <meta-data
        android:name="notifyvisitors_bid_e"
        android:value="DA85CA5D75F7920320C8244AF91D448A"/>

</application>

📘

Note:

In the above example, Dummy Brand ID and Encryption keys are shown. Kindly login to your Notifyvisitors account to see your credentials.

Initialize the SDK

  • Open MainApplication file of your app and Import this statement in MainApplication.java
    a. If you don’t have your Application class, then add this line on your manifest.xml. Otherwise, skip this step
    and follow next.

    android:name="com.capacitor.notifyvisitors.NVApplication"
    

    b. If you have the Application class, Initialize capacitor-notifyvisitors plugin as follows.
    i. Import this statement

    import com.notifyvisitors.notifyvisitors.NotifyVisitorsApplication;
    

    ii. Call register() method in onCreate() method.

    NotifyVisitorsApplication.register(this);
    

IOS

Add this line in capacitor.config.ts

handleApplicationNotifications: false

For Example :

import { CapacitorConfig } from '@capacitor/cli';

const config: CapacitorConfig = {
 appId: 'com.nv.ionic',
 appName: 'NVCapacitorDemo',
 webDir: 'www',
 bundledWebRuntime: false,
 handleApplicationNotifications: false
};


export default config;

Configure your info.plist

  • Open React Native iOS Project into Xcode. Goto Your_ProjectFolder >> ios and open Your_ProjectName.xcworkspace file into Xcode.

  • Goto info.plist of your project (i.e. inside Your_ProjectName Folder into Xcode). Open info.plist file as source code (right click on info.plist and click on Open as >> Source code) and add the following code in it.

<key>NSAppTransportSecurity</key>
 <dict>
   <key>NSAllowsArbitraryLoads</key>
   <true/>
   <key>NSExceptionDomains</key>
   <dict/>
 </dict>
 <key>UIBackgroundModes</key>
   <array>
     <string>fetch</string>
     <string>location</string>
     <string>remote-notification</string>
   </array>
 <key>CFBundleURLTypes</key>
   <array>
     <dict>
       <key>CFBundleURLName</key>
         <string>”Your Project Identifier Name”</string>
       <key>CFBundleURLSchemes</key>
         <array>
           <string>”yourURLscheme”</string>
         </array>
     </dict>
   </array>
 <key>NSLocationAlwaysUsageDescription</key>
    <string>location  is required for geofence</string>
 <key>nvBrandID</key>
    <integer>Your BRANDID comes here</integer>
 <key>nvSecretKey</key>
    <string>Your SECRET KEY comes here</string>
 <key>nvPushCategory</key>
    <string>nvpush</string>
 <key>nvViewAutoRedirection</key>
    <true/>       <!--OR--> <!-- <false/>-->
                                         OR 
  • You can simply open the info.plist and add the keys which works as same as above for this,

    1.1 Add a new row by going to the menu and clicking Editor > Add Item. Setup a NSAppTransportSecurity as a Dictionary.

    1.2 Added a Subkey called NSAllowsArbitraryLoads as Boolean and set its value to YES as follows.

  1. 3 Add a new row again and set up a URL Types item by adding a new item. Expand the URL Types key, expand Item 0, and add a new item, URL schemes. Fill in "appScheme" for Item 0 of URL schemes and your company identifier for the URL Identifier. Your file should resemble the image below when done.

  1. 4 (Optional) Add a new row again and set up a NSLocationWhenInUseUsageDescription as String and fill this field with the message you want to show in the alert box for asking user permission for geofencing (example: location is required for geofence).

  1. 5 (Optional) If your app supports iOS 10 and earlier, add a new row again and set up a NSLocationAlwaysUsageDescription as String and fill this field with the message you want to show in alert box for asking user permission for geofencing (example: location is required for geofence).

  1. 6 Add a new row again and set up a nvBrandID as Number and fill this field with your BRANDID .

  1. 7 Add a new row again and set up a nvSecretKey as String and fill this field with your SECRET KEY .

  1. 8 Add a new row again and set up a nvPushCategory as String and set its value nvpush .

  1. 9 Add a new row again and set up a key nvViewAutoRedirection as Boolean set it YES to enable auto redirection of your app’s ViewControllers from sdk or set it NO to handle redirections by your app.

📘

Note:

In the above example Dummy Brand ID and Secret keys are shown. Kindly log in to your NV_account to see your credentials.

Configure Capabilities

  • Goto Capabilities Tab and turn the Background Modes switch on.To do that select the project from the Project Navigator then select the app target then select the Capabilities tab, and turn the Background Modes switch on.Select 3 check boxes (i.e. Location updates, Background fetch, Remote notifications).

  • In the Capabilities Tab Turn On Push Notifications and if you are upgraded Xcode 8.0 or later and Push Notifications was turned on in previous version turn off Push Notifications and turn it on again to configure push notification properly for the upgraded devices.

  • In the Capabilities Tab Turn On App Groups and click on + sign and add a new app group give the group name as group.nv.{Your App Bundle Identifier}.

Example: if Your App’s Bundle Identifier is com.example.myapp then the App Group must be named as group.nv.com.example.myapp make sure this newly created app group must be checked (Turned on)

Swift-Bridging-Header

  • Add a new header file and name it with the following format. YOUR_PROJECT_NAME-Bridging-Header.h Example if your project name is test. Then the header file name will be test-Bridging-Header.h. Now add the following import statement in YOUR_PROJECT_NAME-Bridging-Header.h for accessing Native SDK Classes.

  • Import header filein Bridging Header

#import "notifyvisitors.h"

Initialise the SDK

iOS 10 Push Notification Handler

  • For iOS 10 Push Notification Add the following Delegate Methods in AppDelegate file.

  • Goto AppDelegate.h import UserNotifications framework and also add UNUserNotificationCenterDelegate to support iOS 10 Push Notification or Rich media push notifications.

import UserNotifications

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {
}

  • Initialize the Plugin in application didFinishLaunchingWithOptions function.
  var nvMode:String? = nil
                #if DEBUG
                nvMode = "debug"
                #else
                    nvMode = "live"
                #endif
   notifyvisitors.initialize(nvMode)
   notifyvisitors.registerPush(withDelegate: self, app: application, launchOptions: launchOptions)

Copy/Update these functions on your app delegate class.

   
func applicationDidEnterBackground(_ application: UIApplication) {
    notifyvisitors.applicationDidEnterBackground(application);
 }


func applicationWillEnterForeground(_ application: UIApplication) {
  notifyvisitors.applicationWillEnterForeground(application);
}


func applicationDidBecomeActive(_ application: UIApplication) {
  notifyvisitors.applicationDidBecomeActive(application);
}


func applicationWillTerminate(_ application: UIApplication) {
  notifyvisitors.applicationWillTerminate();
}


func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey: Any] = [:]) -> Bool {
  notifyvisitors.openUrl(with: app, url: url);
  return ApplicationDelegateProxy.shared.application(app, open: url, options: options)
}


func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool {
  return ApplicationDelegateProxy.shared.application(application, continue: userActivity, restorationHandler: restorationHandler)
}
    
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
  notifyvisitors.didRegisteredNotification(application, deviceToken: deviceToken);
}

func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
  print("push register failed due to the following error = \(error)")
}

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
  notifyvisitors.didReceiveRemoteNotification(userInfo: userInfo);
}

func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
  notifyvisitors.willPresent( notification, withCompletionHandler: completionHandler)
}

func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse) async {
  notifyvisitors.pushNotificationActionData(from: response, autoRedirectOtherApps: true) { (pushData: NSMutableDictionary?) in
    let userInfo: [AnyHashable : Any]?
      if pushData!.count > 0 {
        userInfo = (pushData as! [AnyHashable : Any])
        } else {
        userInfo = [:]
        }
                                                                                          NotificationCenter.default.post(name: Notification.Name.init("didReceiveResponse"), object: nil, userInfo: userInfo) ;                                                                                       }
}

Notification Service Extension

  1. Create a Notification Service Extension in your project. To do that, in Xcode, select File >> New Target and choose the Notification Service Extension template.

  1. Define a name for the Notification Service Extension as given below:

Now close your xcode.

  1. If you already have a Podfile in your project. Please skip this step. Goto your ios folder
    from your project root folder by using the following command.
$ cd platforms && cd ios && pod init
  1. Now open your Xcode and add the notifyvisitors dependency on the pod file under your Notification Service Extension name target like below.
target 'YourNotificationServiceExtension' do
       pod 'notifyvisitors', '6.1.0'
 end
  1. Now Run the following commands in the terminal from the ios folder directory.
pod repo update && pod install && cd .. && cd ..
  • Once the target is created, Activate the scheme for Extension when prompted for the same. After this your extension will be added to project you will see a class with the extension name provided by you while creation and info.plist file associated with it.

  1. Now Open info.plist of your Notification Service Extension as source code (right click on info.plist and click on Open as >> Source code) and add the following code in it.
<key>App Bundle identifier</key>
	<string>”Your App’s Project Identifier Name”</string>
<key>NSExtension</key>
	<dict>
		<key>NSExtensionAttributes</key>
		<dict>
			<key>UNNotificationExtensionDefaultContentHidden</key>
			<true/>
			<key>UNNotificationExtensionInitialContentSizeRatio</key>
			<real>0.7</real>
		</dict>
		<key>NSExtensionPointIdentifier</key>
		<string>com.apple.usernotifications.service</string>
		<key>NSExtensionPrincipalClass</key>
		<string>NotificationService</string>
    </dict>

OR

  • You can simply open the info.plist and add the keys which works as same as above for this.

    6.1 Add a new row by going to the menu and clicking Editor > Add Item. Set a key App Bundle identifier as a String and set its value to your app’s main target Bundle Identifier.

6.2 Expand the NSExtension and add NSExtensionAttributes as Dictionary. Inside NSExtensionAttributes dictionary add a key UNNotificationExtensionDefaultContentHidden as Boolean its value should be YES and add another key UNNotificationExtensionInitialContentSizeRatio as Number its value should be 0.7 as the following preview.

7 Select Notification Service Extension Target from your target and Goto Capabilities Tab Turn On Push Notifications and if you are upgraded Xcode 8.0 or later and Push Notifications was turned on in previous version turn off Push Notifications and turn it on again to configure push notification properly for the upgraded devices.

  1. Capabilities Tab Turn On App Groups and select the app group created previously in the beginning.
    Example: We have previously created an app group named group.nv.com.example.myapp make sure this app group must be visible here and make it checked (Turned on).

  1. Import the header file ServiceExtension.m file.
#import "notifyvisitors.h"
  1. Goto NotificationService.m file and update didReceiveRequestWithContentHandler delegate method as follows:
- (void)didReceiveNotificationRequest:(UNNotificationRequest *)request withContentHandler:(void (^)(UNNotificationContent * _Nonnull))contentHandler {
     self.contentHandler = contentHandler;
     self.bestAttemptContent = [request.content mutableCopy];
     [notifyvisitors LoadAttachmentWithRequest: request BestAttemptContent: self.bestAttemptContent withContentHandler: self.contentHandler];
}

📘

Important

Import the below given library in TypeScript Page for use of NotifyVisitors sdk functions.

Import NotifyVisitors package

import { NotifyVisitors } from 'capacitor-plugin-notifyvisitors'