OneSignal Help & Documentation

Welcome to the OneSignal New IA developer hub. You'll find comprehensive guides and documentation to help you start working with OneSignal New IA as quickly as possible, as well as support if you get stuck. Let's jump right in!

Get Started    Support

React Native SDK Setup

OneSignal React Native SDK Setup Guide. Works with iOS and Android (and derivatives like Amazon).

For Developers

Required For Setup

Expo

If you are building an Expo project, please note that we have recently updated the SDK so that it will no longer crash when you add OneSignal as a dependency inside Expo's development environment. However, please note that until you detach from Expo and link OneSignal's native SDK's (along with React Native's own dependencies), any calls to OneSignal functions will be unused.

Generate Credentials

Before setting up the React Native SDK, you must generate the appropriate credentials for the platform(s) you are releasing on:

iOS - Generate an iOS Push Certificate

Android - Generate a Google Server API Key

Amazon - Generate an Amazon API Key

Running Example project

For your convenience, we created an example project, based on React Native 0.41.2.
You can run this project to test configurations, debug, and build upon it.

  • git clone https://github.com/geektimecoil/react-native-onesignal
  • cd react-native-onesignal && cd examples && cd RNOneSignal
  • yarn
  • Running the iOS example app: react-native run-ios
  • Running the Android example app: react-native run-android

Installation

  1. Add library to project
    • yarn add react-native-onesignal
    • OR npm install --save react-native-onesignal
  2. Link library to project
    • react-native link react-native-onesignal

Android Specific Instructions

In your AndroidManifest.xml, add android:launchMode="singleTop" as an attribute to your main activity. You can also set location permissions.

.....

<!-- Optional - Add the necessary permissions (Choose one of those) -->

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/> <!-- Approximate location - If you want to use promptLocation for letting OneSignal know the user location. -->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/> <!--  Precise location If you want to use promptLocation for letting OneSignal know the user location. -->

<!-- End optional permissions -->


<application ....>
  <activity
    android:name=".MainActivity"
    android:label="OneSignal Example"
    android:launchMode="singleTop"> <!-- Add this attribute to your main activity -->
  </activity>
    .....

We need to check to make sure that react-native-link worked correctly. Inside of MainApplication.java, make sure that you are returning the RNOneSignal package like this. Other dependencies, such as react-native-navigation, will often override the default ReactApplication class, so it is important to make sure you are returning the OneSignal package if you've made changes to this class.

import com.geektime.rnonesignalandroid.ReactNativeOneSignalPackage;

public class MainApplication extends Application implements ReactApplication {

  private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {
    @Override
    protected List<ReactPackage> getPackages() {
      return Arrays.<ReactPackage>asList(
          new MainReactPackage(),
            new ReactNativeOneSignalPackage() // You must return the ReactNativeOneSignalPackage here
      );
    }
  };
  
  @Override
  public List<ReactPackage> createAdditionalReactPackages() {
    return getPackages();
  }
}


NOTE: We've recently added JavaScript react-native initialization of the SDK. You no longer need to add your App ID to the app gradle file. Please see Initializing the SDK for details.

Adding the Gradle Plugin

1. At the very top of your Android project's app/build.gradle, add the following code to the very top of the file:

buildscript {
    repositories {
        maven { url 'https://plugins.gradle.org/m2/' } // Gradle Plugin Portal 
    }
    dependencies {
        classpath 'gradle.plugin.com.onesignal:onesignal-gradle-plugin:[0.10.0, 0.99.99]'
    }
}

apply plugin: 'com.onesignal.androidsdk.onesignal-gradle-plugin'

2. Inside of the android { ... } section in your app/build.gradle, please ensure that your compileSdkVersion and buildToolsVersion is at least API level 26 or higher

android {
    compileSdkVersion 27
    buildToolsVersion '27.0.3'
    // ...
}

iOS Installation

iOS Push Certificate

Add Required Capabilities

  1. Select the root project and Under Capabilities Enable "Push Notifications".
  2. Next Enable "Background Modes" and check "Remote notifications".

Add Notification Service Extension

Required for Incrementing Badge count

You will need Notification Service Extension to increment badge counts using App Groups setup below

This step is optional but highly recommended. The OneSignalNotificationServiceExtension allows your application (in iOS) to receive rich notifications with images and/or buttons. If you do not follow this step, your application will not be able to show images in push notifications, and won't be able to add action buttons to notifications either.

Even if you do not have immediate plans to send push notifications containing images/action buttons, it is still recommended to follow these steps in case you ever decide to change your mind in the future.

  • In Xcode, select File > New > Target
  • Select Notification Service Extension and press Next

    image

  • Enter the product name as OneSignalNotificationServiceExtension and press Finish

    image

  • Press Cancel on the Activate Scheme prompt

    image

By cancelling, you are telling Xcode to continue debugging your application, instead of debugging just the extension. If you activate by accident, you can always switch back to debug your app in Xcode by selecting your application's target (next to the Play button)

  • Go to your Project Settings and select the OneSignalNotificationServiceExtension target.
  • Go to Build Settings and search for Header Search Paths
  • Add $(SRCROOT)/../node_modules/react-native-onesignal/ios and set it as recursive

    image

  • With the OneSignalNotificationServiceExtension target still selected, select the Build Phases tab in Project Settings

  • In Link Binary with Libraries, add the following frameworks:

    • UIKit.framework
    • SystemConfiguration.framework
    • libRCTOneSignal.a

    image

  • Open NotificationServiceExtension.m or NotificationService.swift and replace the whole file contents with the code below:

#import <RCTOneSignalExtensionService.h>

#import "NotificationService.h"

@interface NotificationService ()

@property (nonatomic, strong) void (^contentHandler)(UNNotificationContent *contentToDeliver);
@property (nonatomic, strong) UNNotificationRequest *receivedRequest;
@property (nonatomic, strong) UNMutableNotificationContent *bestAttemptContent;

@end

@implementation NotificationService

- (void)didReceiveNotificationRequest:(UNNotificationRequest *)request withContentHandler:(void (^)(UNNotificationContent * _Nonnull))contentHandler {
    self.receivedRequest = request;
    self.contentHandler = contentHandler;
    self.bestAttemptContent = [request.content mutableCopy];
    
    [RCTOneSignalExtensionService didReceiveNotificationRequest:self.receivedRequest withContent:self.bestAttemptContent];
    
    // DEBUGGING: Uncomment the 2 lines below and comment out the one above to ensure this extension is excuting
    //            Note, this extension only runs when mutable-content is set
    //            Setting an attachment or action buttons automatically adds this
    // NSLog(@"Running NotificationServiceExtension");
    // self.bestAttemptContent.body = [@"[Modified] " stringByAppendingString:self.bestAttemptContent.body];
    
    self.contentHandler(self.bestAttemptContent);
}

- (void)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.
    
    [RCTOneSignalExtensionService serviceExtensionTimeWillExpireRequest:self.receivedRequest withMutableNotificationContent:self.bestAttemptContent];
    
    self.contentHandler(self.bestAttemptContent);
}

@end
import UserNotifications

class NotificationService: UNNotificationServiceExtension {

    var contentHandler: ((UNNotificationContent) -> Void)?
    var bestAttemptContent: UNMutableNotificationContent?
    var receivedRequest : UNNotificationRequest!;

    override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
        self.contentHandler = contentHandler
        bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent)
        self.receivedRequest = request;
        
        RCTOneSignalExtensionService.didReceive(self.receivedRequest, with: self.bestAttemptContent);
        
        if let bestAttemptContent = bestAttemptContent {
            contentHandler(bestAttemptContent)
        }
    }
    
    override 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.
        RCTOneSignalExtensionService.serviceExtensionTimeWillExpireRequest(self.receivedRequest, with: self.bestAttemptContent);
        
        if let contentHandler = contentHandler, let bestAttemptContent =  bestAttemptContent {
            contentHandler(bestAttemptContent)
        }
    }
}

Swift Bridging Header

Make sure to create a separate Objective-C Bridging Header for your OneSignalNotificationExtensionService and add the following import:

#import "RCTOneSignalExtensionService.h"

Ignore any build errors at this point, the next step will import OneSignal which will resolve any errors.

Add App Groups (Optional but Recommended)

In order for your application to be able to let push notifications increment/decrement the badge count, you need to set up an App Group for your application.

Please follow this guide to set up a OneSignal app group in your app.

Initializing the SDK

Both Platforms

OneSignal's react-native SDK now supports JavaScript initialization directly in react native, without having to write native Objective-C code or mess with gradle files.

Native Initialization

While we now support initialization directly in javascript/react, you can still use the older native initialization methods (Objective-C and gradle for iOS and Android respectively). We recommend against doing this, but it is still supported. For information on how to do this, you can read our old readme.

In order to initialize the SDK:

componentWillMount() {
  OneSignal.init("YOUR_ONESIGNAL_APPID");
}

You can also pass in parameters for iOS. These parameters will simply be ignored in Android.

For a full list of supported iOS settings, please see our API reference documentation.

componentWillMount() {
  OneSignal.init("YOUR_ONESIGNAL_APPID", {kOSSettingsKeyAutoPrompt : true});
}

Usage

In your index.android.js or index.ios.js:

import React, { Component } from 'react';
import OneSignal from 'react-native-onesignal'; // Import package from node modules

export default class App extends Component {

    componentWillMount() {
      	OneSignal.init("YOUR_ONESIGNAL_APPID");
      
        OneSignal.addEventListener('received', this.onReceived);
        OneSignal.addEventListener('opened', this.onOpened);
        OneSignal.addEventListener('ids', this.onIds);
    }

    componentWillUnmount() {
        OneSignal.removeEventListener('received', this.onReceived);
        OneSignal.removeEventListener('opened', this.onOpened);
        OneSignal.removeEventListener('ids', this.onIds);
    }

    onReceived(notification) {
        console.log("Notification received: ", notification);
    }

    onOpened(openResult) {
      console.log('Message: ', openResult.notification.payload.body);
      console.log('Data: ', openResult.notification.payload.additionalData);
      console.log('isActive: ', openResult.notification.isAppInFocus);
      console.log('openResult: ', openResult);
    }

    onIds(device) {
		console.log('Device info: ', device);
    }
}

Manually updating iOS OneSignalNativeSDK

When you install react-native-onesignal it will automaticly include a specific version of the OneSignal iOS native SDK that is known to work with it. Only follow the instructions below if there is a native OneSignal SDK fix you need that isn't included already in the latest react-native-onesignal update.

  1. Download the latest OneSignal iOS native release.
  2. Delete libOneSignal.a and OneSignal.h from node_modules/react-native-onesignal/ios/
  3. From /iOS_SDK/OneSignalSDK/Framework/OneSignal.framework/Versions/A/, copy OneSignal to /node_modules/react-native-onesignal/ios/ and rename it libOneSignal.a
  4. Copy OneSignal.h from /iOS_SDK/OneSignalSDK/Framework/OneSignal.framework/Versions/A/ to /node_modules/react-native-onesignal/ios/

Problems/Errors?

If you are having trouble with our SDK, please see our Troubleshooting guide.

React Native SDK Setup

OneSignal React Native SDK Setup Guide. Works with iOS and Android (and derivatives like Amazon).

For Developers