Hey! These docs are for version 7.0, which is no longer officially supported. Click here for the latest version, 9.0!

Ionic & Capacitor SDK Setup

Instructions for adding the OneSignal SDK to your Ionic or Capacitor app for iOS, Android, Amazon Fire apps

👍

OneSignal Cordova SDK Version 3 - Beta!

Take a look at our OneSignal Cordova SDK documentation to learn more about the Cordova 2.x to 3.0.0 upgrade.

We are looking for feedback. Help us make our SDK better. Leave your feedback in this Github issue.

GitHub repo: Ionic + Capacitor (ReactJS) Example app using the SDK Version 3.

📘

Looking for PhoneGap or Cordova setup?

See our Cordova SDK Setup if you are using Cordova framework directly.

Step 1 - Requirements

  • OneSignal supports Ionic versions 1 through 5 and Capacitor.
  • A OneSignal Account if you do not already have one
  • Your OneSignal App ID, available in Settings > Keys & IDs
  • Cordova 8.0.0 or newer - You should also remove other Push SDKs that you are not using, otherwise you may see duplicate notifications.
  • Capacitor 2.0.0 or newer - You should also remove other Push SDKs that you are not using, otherwise you may see duplicate notifications.
  • iOS - An iOS device (iPhone, iPad, iPod Touch) to test on. The Xcode simulator doesn't support push notifications so you must test on a real device.
  • iOS - You MUST have a Mac with a new version of Xcode

iOS - Generate an iOS Push Certificate.

Android - Generate a Google Firebase Server API Key

Amazon - Generate an Amazon API Key

Update the OneSignal SDK

If you already have an app with the OneSignal Ionic SDK, you can run this to ensure your SDK is on the latest version. Otherwise, proceed to the next step to add OneSignal.

ionic cordova plugin remove onesignal-cordova-plugin
ionic cordova plugin add onesignal-cordova-plugin

If you are using Capacitor and already have an app with the OneSignal SDK, run the following to ensure your SDK is on the latest version.

npm uninstall onesignal-cordova-plugin
npm install onesignal-cordova-plugin
npx cap sync

🚧

Xcode 10 Notice

To prevent Mismatched User errors, upgrade cordova-ios to 5.0.0 or newer.

Step 2 - Add the OneSignal SDK

iOS Requirements

sudo gem install cocoapods
pod repo update

Android Requirements

  • Cordova [email protected] or newer - To ensure compatibility with other Cordova plugins.

2.1 Import the OneSignal Cordova Plugin

Run the following from your project directory.

npm install onesignal-cordova-plugin
npx cap sync
ionic cordova plugin add onesignal-cordova-plugin --save
ionic plugin add onesignal-cordova-plugin --save

2.2 Add required code

📘

OneSignal Typescript Ionic Native wrapper

Optionally you can use the OneSignal Typescript Ionic Native wrapper instead of following the instructions below.

When creating a new Ionic + Capacitor project inside of the Ionic Dashboard or using the CLI, you get the option to choose what kind of project you want to create.

Option A: Ionic + Capacitor(Angular)
Option B: Ionic + Capacitor (ReactJS)

Option A: Integrating OneSignal SDK into your Ionic + Capacitor (Angular) project.

If you are using the basic Ionic starter project add the following to your <project-dir>/src/app/app.component.ts.

//Remove this method to stop OneSignal Debugging 
window.plugins.OneSignal.setLogLevel({logLevel: 6, visualLevel: 0});

var notificationOpenedCallback = function(jsonData) {
    console.log('notificationOpenedCallback: ' + JSON.stringify(jsonData));
};

// Set your iOS Settings
var iosSettings = {};
iosSettings["kOSSettingsKeyAutoPrompt"] = false;
iosSettings["kOSSettingsKeyInAppLaunchURL"] = false;

window.plugins.OneSignal
    .startInit("YOUR_ONESIGNAL_APP_ID")
    .handleNotificationOpened(notificationOpenedCallback)
    .iOSSettings(iosSettings)
    .inFocusDisplaying(window.plugins.OneSignal.OSInFocusDisplayOption.Notification)
    .endInit();

// The promptForPushNotificationsWithUserResponse function 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 6)
window.plugins.OneSignal.promptForPushNotificationsWithUserResponse(function(accepted) {
    console.log("User accepted notifications: " + accepted);
});
// Add the following to your existing ready fuction.

constructor(platform: Platform, statusBar: StatusBar, splashScreen: SplashScreen) {
  platform.ready().then(() => {
    statusBar.styleDefault();
    splashScreen.hide();
    
    //Remove this method to stop OneSignal Debugging 
    window["plugins"].OneSignal.setLogLevel({logLevel: 6, visualLevel: 0});
    
    var notificationOpenedCallback = function(jsonData) {
      console.log('notificationOpenedCallback: ' + JSON.stringify(jsonData));
    };
    
    // Set your iOS Settings
    var iosSettings = {};
    iosSettings["kOSSettingsKeyAutoPrompt"] = false;
    iosSettings["kOSSettingsKeyInAppLaunchURL"] = false;
    
    window["plugins"].OneSignal
      .startInit("YOUR_ONESIGNAL_APP_ID")
      .handleNotificationOpened(notificationOpenedCallback)
      .iOSSettings(iosSettings)
      .inFocusDisplaying(window["plugins"].OneSignal.OSInFocusDisplayOption.Notification)
      .endInit();
    
    // The promptForPushNotificationsWithUserResponse function 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 6)
    window["plugins"].OneSignal.promptForPushNotificationsWithUserResponse(function(accepted) {
      console.log("User accepted notifications: " + accepted);
    });
  });
}
// Add the following to your existing ready fuction.

.run(function($ionicPlatform) {
  $ionicPlatform.ready(function() {
    // Enable to debug issues.
  // window.plugins.OneSignal.setLogLevel({logLevel: 4, visualLevel: 4});
  
  var notificationOpenedCallback = function(jsonData) {
    console.log('notificationOpenedCallback: ' + JSON.stringify(jsonData));
  };

  window.plugins.OneSignal
    .startInit("YOUR_APPID")
    .handleNotificationOpened(notificationOpenedCallback)
    .endInit();
})

Replace YOUR_ONESIGNAL_APP_ID with your OneSignal AppId, available in Settings > Keys & IDs.

Option B: Integrating OneSignal SDK into your Ionic + Capacitor (ReactJS) project.

If you are using the basic Ionic starter project add the following to your <project-dir>/src/App.tsx.

//Remove this method to stop OneSignal Debugging 
window.plugins.OneSignal.setLogLevel({logLevel: 6, visualLevel: 0});

var notificationOpenedCallback = function(jsonData) {
    console.log('notificationOpenedCallback: ' + JSON.stringify(jsonData));
};

// Set your iOS Settings
var iosSettings = {};
iosSettings["kOSSettingsKeyAutoPrompt"] = false;
iosSettings["kOSSettingsKeyInAppLaunchURL"] = false;

window.plugins.OneSignal
    .startInit("YOUR_ONESIGNAL_APP_ID")
    .handleNotificationOpened(notificationOpenedCallback)
    .iOSSettings(iosSettings)
    .inFocusDisplaying(window.plugins.OneSignal.OSInFocusDisplayOption.Notification)
    .endInit();

// The promptForPushNotificationsWithUserResponse function 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 6)
window.plugins.OneSignal.promptForPushNotificationsWithUserResponse(function(accepted) {
    console.log("User accepted notifications: " + accepted);
});

2.3 Add Android Icons (For Android Apps)

Follow the Custom Notification Icons instructions below to create a small notification icon required for Android 5.0+ devices.

2.4 Add Amazon ADM Support (For Kindle Fire Apps)

Place your api_key.txt file into your <project-dir>/platforms/android/assets/ folder.

To create an api_key.txt for your app follow our Generate an Amazon API Key

Step 3 - Configure your Xcode project (iOS Only)

3.1 Open <project-root>/platform/ios/YourAppName.xcworkspace
3.2 Select the Root Project > Your Main App Target > Under Signing & Capabilities > Click "+ Capability" to add Push Notifications and Background Modes.
3.3 Within Background Modes and check Remote notifications.

1531

3.4 Add a Service Extension (Recommended)

The OneSignalNotificationServiceExtension allows your application (in iOS) to receive rich notifications with images and/or buttons, along with Badges and advanced analytics like Outcomes.

3.5 In Xcode Select File > New > Target...
3.6 Select Notification Service Extension then press Next.

730

3.7 Enter the product name as OneSignalNotificationServiceExtension and select Objective-C for the language. Then press Finish.

Do not select Activate on the dialog that is shown after selecting Finish.

729

3.8 Press Cancel on the Activate scheme prompt.

425

By canceling, you are keeping Xcode debugging your app, instead of the extension you just created.

If you activated by accident, you can switch back to debug your app within Xcode (next to the play button).

3.9 In the project navigator, select the top-level project directory and select the OneSignalNotificationServiceExtension target in the project and targets list.

Unless you have a specific reason not to, you should set the Deployment Target to be iOS 10 which is the version of iOS that Apple released Rich Media for push. iOS versions under 10 will not be able to get Rich Media.

1531

3.10 In the project navigator, click the OneSignalNotificationServiceExtension folder and open the NotificationService.m file and replace the whole file's contents with the following code.

#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];
    
    // Uncomment this line to set the default log level of NSE to VERBOSE so we get all logs from NSE logic
    //[OneSignal setLogLevel:ONE_S_LL_VERBOSE visualLevel:ONE_S_LL_NONE];
    
    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

Ignore any build errors at this point. We will import OneSignal which will resolve any errors.

1722

3.11 Select the new OneSignalNotificationServiceExtension Target, select "Build Settings" then search for Code Signing Entitlements.

3.12 Delete both Debug and Release entries so they are blank.

1722

3.13 Select Build Phases and expanded the"Link Binary With Libraries" section.
3.14 Press the + and add:

  • SystemConfiguration.framework
  • UIKit.framework
  • CoreGraphics.framework
  • WebKit.framework
943

3.15 Press the + again and click Add Other... > Add Files...

1325

3.16 Navigate to > platforms > ios > Pods > OneSignal > iOS_SDK > OneSignalSDK > Framework > Select OneSignal.framework and click Open

1864

3.17 You should now see all 5 frameworks

1531

3.18 Add an iOS App Group (CLI ONLY)

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

📘

Troubleshooting

If you run into any errors see Troubleshooting Cordova Variants, our our general Troubleshooting section.

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

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.

1200

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

Step 6 - 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.

  • Ionic SDK API - Explore other methods available in our Ionic 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..