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
- A OneSignal Account if you do not already have one
- Your OneSignal App ID, available in Keys & IDs
- Expo Developers - You will have to eject in order to complete the following steps since OneSignal is a Native SDK.
iOS - Generate an iOS Push Certificate. You should generate a certificate after adding the Push Notification capability while setting up your iOS app.
Android - Generate a Google Firebase 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 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
- Open the
Step 2 - Add the OneSignal package to your app
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
- Add RCTOneSignal project into Libraries manually (click here for a screenshot):
- Open
node_modules/react-native-onesignal/ios
- Then, drag and drop
RCTOneSignal.xcodeproj
into XCode project folderLibraries
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.
In the meantime, there is an easier way to add Jetifier than following Google's guide above. 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
Select the root project in Xcode and under Capabilities, enable "Push Notifications".
Next Enable "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
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
Make sure to run pod install
again.
- Open
NotificationService.m
orNotificationService.swift
and 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.
Please follow the iOS SDK App Groups setup guide to add the OneSignal App Group in your app.
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.
- Download the latest OneSignal iOS native release.
- Delete
libOneSignal.a
andOneSignal.h
fromnode_modules/react-native-onesignal/ios/
- From
/iOS_SDK/OneSignalSDK/Framework/OneSignal.framework/Versions/A/
, copyOneSignal
to/node_modules/react-native-onesignal/ios/
and rename itlibOneSignal.a
- Copy
OneSignal.h
from/iOS_SDK/OneSignalSDK/Framework/OneSignal.framework/Versions/A/Headers
to/node_modules/react-native-onesignal/ios/
Step 7 - 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 8 - 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 9 - 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..
Updated almost 2 years ago