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    Discussions

React Native & Expo SDK Setup

Instructions for adding the OneSignal React Native & Expo SDK to your app for iOS, Android, and derivatives like Amazon

Step 1 - Requirements

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/OneSignal/react-native-onesignal
  • cd react-native-onesignal && cd examples && cd RNOneSignal
  • yarn
  • Running the Android example app: react-native run-android
  • Running the iOS example app:
    • Open the RNOneSignal project in Xcode
    • Change the Signing Team and Bundle Identifier for both the RNOneSignal target as well as the OneSignalNotificationServiceExtension
      • The Service Extension bundle id should be .OneSignalNotificationServiceExtension
    • Build

Step 2 - Add the OneSignal package to your app

🚧

Migrate to Expo’s Bare Workflow, if necessary.

Since OneSignal is a native library and leverages the Google FCM and Apple APNS protocols, OneSignal is only supported in the Expo Bare Workflow.

To begin using OneSignal, make sure you are already using the Bare Workflow, or follow Expo’s guide on Ejecting from the Managed Workflow.

2.1 Install the SDK using Yarn or NPM

  • Yarn: yarn add react-native-onesignal
  • NPM npm install --save react-native-onesignal

2.2 Link OneSignal

React Native: react-native link react-native-onesignal
Expo: expo install react-native-onesignal

🚧

If you use React Native version 0.59.0 or older AND you are not using Cocoapods

If react-native link react-native-onesignal does not work

  • Open node_modules/react-native-onesignal/ios
  • Then, drag and drop RCTOneSignal.xcodeproj into XCode project folder Libraries

Step 3 - Install for Android using Gradle (For Android apps)

3.1 In your AndroidManifest.xml, add android:launchMode="singleTask" as an attribute to your main activity.

Expo users may already have this attribute set to "singleTask" and can skip to step 3.2.

.....

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

3.2 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.12.6, 0.99.99]'
    }
}

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

3.3 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.

Expo can find these values in android/build.gradle.

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

3.4 Ensure AndroidX compatibility

Required for projects running React Native 0.60.0+
The OneSignal SDK is not yet upgraded to AndroidX. Luckily, Google created a tool called Jetifier that will migrate the imports, even for compiled .jar.

Jetifier should automatically run in this case, if not, you can add an npm package called jetifier, noted from React Native 0.60.0 release notes.

Step 4 - Install for iOS using Cocoapods (For iOS Apps)

4.1 Run cd ios && pod install && cd ..

4.2 Add Required Capabilities

In Xcode, select the root project and main app target. In Signing & Capabilities, select All and + Capability. Add "Push Notifications" and Background Modes

Click + Capability to add Background Modes and check Remote notifications.

4.3 Add a Notification Service Extension

The OneSignalNotificationServiceExtension allows your application to receive rich notifications with images and/or buttons, and to report analytics about which notifications users receive.

4.3.1 In Xcode Select File > New > Target...
4.3.2 Select Notification Service Extension then press Next.

4.3.3 Enter the product name as OneSignalNotificationServiceExtension and press Finish. Do not press "Activate" on the dialog shown after this.

4.3.4 Press Cancel on the Activate scheme prompt.

By canceling, you are keeping Xcode debugging your app, instead of just the extension. If you activate by accident, you can always switch back to debug your app within Xcode (next to the play button).

4.3.5 In the Project Navigator, select the top-level project directory and select the OneSignalNotificationServiceExtension target in the project and targets list.

Ensure the Deployment Target is set to iOS 10 for maximum platform compatibility.

4.3.6 Finish Notification Service Extension Setup

If you did not use Cocoapods, follow these steps.

Otherwise, continue with the following setup:

  • In your Project Root > iOS > Podfile, add the notification service extension outside the main target (should be at the same level as your main target):
target 'OneSignalNotificationServiceExtension' do
  pod 'OneSignal', '>= 2.9.3', '< 3.0'
end

Close Xcode. While still in the ios directory, run pod install again.

  • Open the . xcworkspace file in Xcode. In the OneSignalNotificationServiceExtension directory > NotificationService.m or NotificationService.swift file, replace the whole file contents with the code below:
#import <OneSignal/OneSignal.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];
    
    [OneSignal didReceiveNotificationExtensionRequest:self.receivedRequest withMutableNotificationContent: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.
    
    [OneSignal serviceExtensionTimeWillExpireRequest:self.receivedRequest withMutableNotificationContent:self.bestAttemptContent];
    
    self.contentHandler(self.bestAttemptContent);
}

@end
import UserNotifications

import OneSignal

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

Ignore any build errors at this point, we will resolve these later by importing the OneSignal library.

4.4 Add App Group

In order for your application to use Confirmed Deliveries and increment/decrement Badges through push notifications, you need to set up an App Group for your application.

4.4.1 In your main app target go back to Signing & Capabilities > All > + Capability and add App Groups

4.4.2 Under the newly added “App Groups” capability click the + button.

Set the “App Groups” container to be group.YOUR_BUNDLE_IDENTIFIER.onesignal where YOUR_BUNDLE_IDENTIFIER is the same as shown in "Bundle Identifier" then press OK.

4.4.3 Repeat this process for the OneSignalNotificationServiceExtension

Make sure the "App Groups" container is the same for both targets! Do not include OneSignalNotificationServiceExtension. Then press OK.

If you require more details or troubleshooting help, see the iOS SDK App Groups setup guide.

Step 5 - Initialize the OneSignal SDK

OneSignal's react-native SDK now supports JavaScript initialization directly in react native, without having to write native 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). This is no longer recommended. But for information on how to do this, you can read our old readme.

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

In your App.js or index.js:

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

export default class App extends Component {

constructor(properties) {
  super(properties);
  //Remove this method to stop OneSignal Debugging 
  OneSignal.setLogLevel(6, 0);
  
  // Replace 'YOUR_ONESIGNAL_APP_ID' with your OneSignal App ID.
  OneSignal.init("YOUR_ONESIGNAL_APP_ID", {kOSSettingsKeyAutoPrompt : false, kOSSettingsKeyInAppLaunchURL: false, kOSSettingsKeyInFocusDisplayOption:2});
  OneSignal.inFocusDisplaying(2); // Controls what should happen if a notification is received while the app is open. 2 means that the notification will go directly to the device's notification center.
  
  // The promptForPushNotifications function code will show the iOS push notification prompt. We recommend removing the following code and instead using an In-App Message to prompt for notification permission (See step below)
  OneSignal.promptForPushNotificationsWithUserResponse(myiOSPromptCallback);

   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);
  }
}
function myiOSPromptCallback(permission){
    // do something with permission value
}

🚧

Event Listeners & Components

We suggest using a base/root component to add as an event listener. If you choose a sub-component that is only shown in some situations (such as using a homepage as an event listener), the component may unmount later on as the user navigates elsewhere in your app.

If you encounter problems with one or more of the events listeners, please see our troubleshooting documentation here.

Manually updating iOS OneSignalNativeSDK

When you install react-native-onesignal it will automatically 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/Headers to /node_modules/react-native-onesignal/ios/

Step 6 - Run your app and send yourself a notification

Build and test your app to make sure your device is successfully subscribed to notifications and that you can receive notifications sent from the OneSignal dashboard.

📘

Problems/Errors?

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

Step 7 - Implement a Soft-Prompt In-App Message for iOS

Android devices are subscribed to notifications automatically when your app is installed, so this section only applies to your iOS release.

Apple's Human Interface Guidelines recommend that apps "Create an alert, modal view, or other interface that describes the types of information they want to send and gives people a clear way to opt in or out."

OneSignal provides an easy option for a "soft-prompt" using In-App Messages to meet this recommendation and have a better user experience. This also permits you to ask for permission again in the future, since the native permission prompt can no longer be shown in your app if the user clicks deny.

See our iOS Push Opt-In Prompt for details on implementing this.

Step 8 - Implement other OneSignal Features

  • Notification Delivery Settings - Learn about the many customizations and methods you can use to send notifications to your users in our Sending Push Messages guide.

  • Automated Messages - Set up Automated Messages to automatically re-engage app users who have lapsed or abandoned their cart. Learn more in our Automated Messages guide.

  • Segments and Tags - OneSignal supports simple and powerful tagging and segmentation to send messages to relevant users through our dashboard and API. Learn more in our Segments guide.

  • In-App Messages - OneSignal supports In-App Messaging in order to display rich content to your users or to present permission prompts, surveys, promotions, announcements, and more. Learn more in our In-App Messaging Overview.

  • E-Mail Support - OneSignal supports the delivery and automation of e-mail in addition to push notifications. Learn more in our Email Overview.

  • React Native SDK API - Explore other methods available in our React Native SDK API Documentation.

  • Remote API - Send notifications, import data, and export data using our simple and powerful API. Learn more in our OneSignal API overview..

Common Troubleshooting steps:

Could not determine the dependencies of task ':app:installDebug'.

SDK location not found. Define location with an ANDROID_SDK_ROOT environment variable or by setting the sdk.dir path in your project's local properties file at '/Users/user/react-native-onesignal/examples/RNOneSignal/android/local.properties'.

Open the > android directory and add a file called local.properties

Within local.properties place your android sdk path, should be similar to this but replace with your directory path:

sdk.dir = /Users/jononesignal/Library/Android/sdk

Updated about a month ago


React Native & Expo SDK Setup


Instructions for adding the OneSignal React Native & Expo SDK to your app for iOS, Android, and derivatives like Amazon

Suggested Edits are limited on API Reference Pages

You can only suggest edits to Markdown body content, but not to the API spec.