How do you implement OneSignal?

Author: Liang

Mar. 07, 2024

Electrical Equipment & Supplies

Requirements

Requirements

Setup

Setup

1. Add Capabilities

1. Add Capabilities

This step will make sure your project is able to receive remote/push notifications.

Select the root project > your main app target > Signing & Capabilities.

If you do not see Push Notifications enabled, click + Capability and add Push Notifications.

Click + Capability again and add Background Modes. Then check Remote notifications.

2. Add Notification Service Extension

2. Add Notification Service Extension

The OneSignalNotificationServiceExtension allows your iOS application to receive rich notifications with images, buttons, and badges. It's also required for OneSignal's Confirmed Delivery analytics features.

In Xcode Select File > New > Target...

Select Notification Service Extension then Next.

Enter the product name as OneSignalNotificationServiceExtension and press Finish.

Do not activate the scheme on the dialog that is shown after selecting "Finish".

Press Cancel on the Activate scheme prompt.

By canceling, you keep Xcode debugging your app instead of the extension you just created. If you activated by accident, you can switch back to debug your app target (middle-top next to the device selector).

Select the OneSignalNotificationServiceExtension target and General settings.

Set Minimum Deployments to be the same value as your Main Application Target. This should be iOS 11 or higher.

Set the OneSignalNotificationServiceExtension Target Minimum Deployments value to be the same as your Main Application Target.

3. Add App Groups

3. Add App Groups

App Groups allow your app and the OneSignalNotificationServiceExtension to communicate when a notification is received, even if your app is not active. This is required for badges and Confirmed Deliveries.

Select your Main App Target > Signing & Capabilities > + Capability > App Groups.

Within App Groups, click the + button.

Set the App Groups container to be group.YOUR_BUNDLE_IDENTIFIER.onesignal where YOUR_BUNDLE_IDENTIFIER is the same as your Main Application "Bundle Identifier".

Press OK and repeat for the OneSignalNotificationServiceExtension Target.

Select the OneSignalNotificationServiceExtension Target > Signing & Capabilities > + Capability > App Groups.

Within App Groups, click the + button.

Set the App Groups container to be group.YOUR_BUNDLE_IDENTIFIER.onesignal where YOUR_BUNDLE_IDENTIFIER is the same as your Main Application "Bundle Identifier".

DO NOT INCLUDE OneSignalNotificationServiceExtension.

Do not include OneSignalNotificationServiceExtension

Optional instructions to setup custom App Group Name (click to expand)

This step is only required if you do not want to use the default app group name (which is group.{your_bundle_id}.onesignal).

Open your Info.plist file and add a new OneSignal_app_groups_key as a String type.

Enter the group name you checked in the last step as it's value.

Make sure to do the same for the Info.plist under the OneSignalNotificationServiceExtension folder.

4. Add SDK

4. Add SDK

Swift Package Manager

Swift Package Manager

The OneSignal SDK can be added as a Swift Package (works with Objective-C as well).

Instructions on adding OneSignal with Swift Package Manager (click to expand)

Select your Project > Package Dependencies > + button.


Enter Package URL: https://github.com/OneSignal/OneSignal-XCFramework

Make sure Dependency Rule is set to Up to Next Major Version

Click Add Package


Add the libraries to the following packages as directed. Note that if you do not include the OneSignalInAppMessages and OneSignalLocation libraries, you will not have access to those features.

  • Required: OneSignalExtension to the OneSignalNotificationServiceExtension Target.
  • Required: OneSignalFramework to your Application Target.
  • Recommended: OneSignalInAppMessages to your Application Target.
  • Optional: OneSignalLocation to your Application Target.

Click Add Package.

In this example, we exclude the OneSignalLocation library and therefore will not have access to storing location within OneSignal.


Select your Application Target > General > Frameworks, Libraries, and Embedded Content.

Check to ensure the required OneSignalFramework and other optionally selected libraries (OneSignalInAppMessages and OneSignalLocation) have been added.

In this example, we correctly see the OneSignalFramework and OneSignalInAppMessages libraries are added. The OneSignalLocation library is missing because we excluded it in the previous step.


Select the OneSignalNotificationServiceExtension Target > General > Frameworks and Libraries.

Check to ensure the required OneSignalFramework and other optionally selected libraries (OneSignalInAppMessages and OneSignalLocation) have been added.

CocoaPods

CocoaPods

The OneSignal SDK can be added with CocoaPods.

Instructions on adding OneSignal with CocoaPods (click to expand)

Ensure your installed Cocoapods version is 1.12.1 or newer!

Close your current Xcode project and in the project root, run sudo gem install cocoapods.

Run pod init from the terminal in your project directory.

Open the newly created Podfile with your favorite code editor.

Add the OneSignal dependency under your project name target as well as
OneSignalNotificationServiceExtension target like below.

target 'your_project_name' do
  pod 'OneSignal/OneSignal', '>= 5.0.0', '< 6.0'
  pod 'OneSignal/OneSignalInAppMessages', '>= 5.0.0', '< 6.0'
  # If your app does not use CoreLocation, you can remove this:
  pod 'OneSignal/OneSignalLocation', '>= 5.0.0', '< 6.0'
  # Your other pods here
end

target 'OneSignalNotificationServiceExtension' do
  pod 'OneSignal/OneSignal', '>= 5.0.0', '< 6.0'
  pod 'OneSignal/OneSignalInAppMessages', '>= 5.0.0', '< 6.0'
  # If your app does not use CoreLocation, you can remove this:
  pod 'OneSignal/OneSignalLocation', '>= 5.0.0', '< 6.0'
end

Run the following commands in your terminal in your project directory.

pod repo update
pod install

Open the newly created <project-name>.xcworkspace file.

Make sure to always open the workspace from now on. You can also do this automatically by running xed . from the root of your project.

5. Initialization

5. Initialization

Storyboard

Storyboard

If using the Storyboard, navigate to your AppDelegate file and add the OneSignal initialization code to didFinishLaunchingWithOptions. Replace YOUR_ONESIGNAL_APP_ID with your OneSignal App ID.

Make sure to import the OneSignal headers:

  • Swift: import OneSignalFramework
  • Objective-C: #import <OneSignalFramework/OneSignalFramework.h>

import UIKit
import OneSignalFramework

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
  
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: 
[UIApplication.LaunchOptionsKey: Any]?) -> Bool {
  
  // Remove this method to stop OneSignal Debugging
  OneSignal.Debug.setLogLevel(.LL_VERBOSE)
  
  // OneSignal initialization
  OneSignal.initialize("YOUR_ONESIGNAL_APP_ID", withLaunchOptions: launchOptions)
  
  // requestPermission will show the native iOS notification permission prompt.
  // We recommend removing the following code and instead using an In-App Message to prompt for notification permission
  OneSignal.Notifications.requestPermission({ accepted in
    print("User accepted notifications: \(accepted)")
  }, fallbackToSettings: true)
  
  // Login your customer with externalId
  // OneSignal.login("EXTERNAL_ID")
  
  return true
}
  
// Remaining contents of your AppDelegate Class...
}
#import <OneSignalFramework/OneSignalFramework.h>

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
  
  // Remove this method to stop OneSignal Debugging  
  [OneSignal.Debug setLogLevel:ONE_S_LL_VERBOSE];
  
  // OneSignal initialization
  [OneSignal initialize:@"YOUR_ONESIGNAL_APP_ID" withLaunchOptions:launchOptions];

  // requestPermission will show the native iOS notification permission prompt.
  // We recommend removing the following code and instead using an In-App Message to prompt for notification permission
  [OneSignal.Notifications requestPermission:^(BOOL accepted) {
    NSLog(@"User accepted notifications: %d", accepted);
  } fallbackToSettings:true];
  
  // Login your customer with externalId
  // [OneSignal login:@"EXTERNAL_ID"];
  
  return YES;
}

SwiftUI

SwiftUI

If using SwiftUI, update your main 'APP_NAME'App.swift file and add the OneSignal initialization code. Replace YOUR_ONESIGNAL_APP_ID with your OneSignal App ID.

import SwiftUI
import OneSignalFramework

@main
struct YOURAPP_NAME: App {
    @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
    
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}

class AppDelegate: NSObject, UIApplicationDelegate {
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
       // Remove this method to stop OneSignal Debugging
       OneSignal.Debug.setLogLevel(.LL_VERBOSE)
        
       // OneSignal initialization
       OneSignal.initialize("YOUR_ONESIGNAL_APP_ID", withLaunchOptions: launchOptions)

       // requestPermission will show the native iOS notification permission prompt.
       // We recommend removing the following code and instead using an In-App Message to prompt for notification permission
       OneSignal.Notifications.requestPermission({ accepted in
         print("User accepted notifications: \(accepted)")
       }, fallbackToSettings: true)

       // Login your customer with externalId
       // OneSignal.login("EXTERNAL_ID")
            
       return true
    }
}

OneSignalNotificationServiceExtension

OneSignalNotificationServiceExtension

In the project navigator, select the OneSignalNotificationServiceExtension folder and open the NotificationService.m or NotificationService.swift file.

Replace the whole file's contents with the following code.

import UserNotifications

import OneSignalExtension

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
        self.bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent)
        
        if let bestAttemptContent = bestAttemptContent {
            /* DEBUGGING: Uncomment the 2 lines below to check this extension is executing
                          Note, this extension only runs when mutable-content is set
                          Setting an attachment or action buttons automatically adds this */
            // print("Running NotificationServiceExtension")
            // bestAttemptContent.body = "[Modified] " + bestAttemptContent.body
            
            OneSignalExtension.didReceiveNotificationExtensionRequest(self.receivedRequest, with: bestAttemptContent, withContentHandler: self.contentHandler)
        }
    }
    
    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 {
            OneSignalExtension.serviceExtensionTimeWillExpireRequest(self.receivedRequest, with: self.bestAttemptContent)
            contentHandler(bestAttemptContent)
        }
    }  
}
#import <OneSignalExtension/OneSignalExtension.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];
    
    /* DEBUGGING: Uncomment the 2 lines below and comment out the one above to ensure this extension is executing
                  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];
    
    [OneSignalExtension didReceiveNotificationExtensionRequest:self.receivedRequest
                       withMutableNotificationContent:self.bestAttemptContent
                                   withContentHandler:self.contentHandler];
}

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

@end

Example of the NotificationService.swift file.

6. Testing

6. Testing

Run your app on a physical device to make sure it builds correctly.

If you used the provided code, then the requestPermission method, should prompt you to subscribe to push notifications. You can change this later.

Check your OneSignal Dashboard Audience > Subscriptions to see your User & Subscription Record.

Then head over to Messages > New Push to send your first Push Notification from OneSignal.

📘

Troubleshooting

If running into issues, see our Mobile Troubleshooting Guide.

Try our example projects on our Github repository.

If stuck, or email [email protected] for help.

For faster assistance, please provide:

  • Your OneSignal App ID
  • Details, logs, and/or screenshots of the issue.
  • Steps to reproduce

Recommended

Recommended

Push permission with In-App Message

Push permission with In-App Message

You can continue to opt-in users to push via the requestPermission method. However, Apple's Human Interface Guidelines recommends 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 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 is limited to how many times it can show and cannot be shown again if the user clicks deny.

See How to Prompt for Push Permissions with In-App Messages for details on implementing this.

Identify Users

Identify Users

Required if using integrations.
Recommended for messaging across multiple channels (push, email, sms).

OneSignal creates subscription-level records under a unique ID called the subscription_id. A single user can have multiple subscription_id records based on how many devices, email addresses, and phone numbers they use to interact with your app.

If your app has its own login system to track users, call login at any time to link all channels to a single user. For more details, see Aliases & External ID.

let externalId = "123456789" // You will supply the external id to the OneSignal SDK
OneSignal.login(externalId)
NSString* externalUserId = @"123456789"; // You will supply the external user id to the OneSignal SDK
[OneSignal login:externalUserId];

Set Email and Phone Number

Set Email and Phone Number

Recommended if using Email and SMS messaging.

Use the provided SDK methods to capture email and phone number when provided. Follow the channel quickstart guides for setup:

// Pass in email provided by customer
OneSignal.User.addEmail("[email protected]")

// Pass in phone number provided by customer
OneSignal.User.addSms("+11234567890")
// Pass in email provided by customer
[OneSignal.User addEmail:@"[email protected]"];

// Pass in phone number provided by customer
[OneSignal.User addSms:@"+11234567890"];

Add Data Tags

Optional

Tags are custom key : value pairs of String data used for tracking user events and properties. Setting tags is required for more complex segmentation and message personalization.

See Data Tags for more details.

OneSignal.User.addTag(key: "key", value: "value")
[OneSignal.User addTagWithKey:@"key" value:@"value"];

Requirements

Requirements

Setup

Setup

1. Add SDK

1. Add SDK

Open your App build.gradle (Module: app) file, add the following to your dependencies section.

A Gradle build defines the project and its tasks and dependancies. Here we are declaring the OneSignal SDK as an external dependancy for the project. For more details, please view Gradle's documentation on Build Scripts.

implementation 'com.onesignal:OneSignal:[5.0.0, 5.99.99]'
implementation("com.onesignal:OneSignal:[5.0.0, 5.99.99]")

👍

Sync Gradle

Make sure to press "Sync Now" on the banner that pops up after saving!

2. Initialization

2. Initialization

Important

Add the following code to the onCreate method in your Application class. If you don't have an Application class follow our Create Application Class Guide.

The SDK needs an Android Context to listen to foreground changes to the app. An Activity is also a Context so the SDK can utilize it, however if you only initialize OneSignal in MainActivity it may not cover all the entry points to your app. Also, there are edge cases such as the app being cold started but resuming to a specific Activity where it's not going to trigger the onCreate on your MainActivity. This is why we recommend following the Create Application Class Guide.

Your ONESIGNAL_APP_ID can be found in the dashboard Settings > Keys & IDs.

import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

import com.onesignal.OneSignal
import com.onesignal.debug.LogLevel

// NOTE: Replace the below with your own ONESIGNAL_APP_ID
const val ONESIGNAL_APP_ID = "########-####-####-####-############"
  
class ApplicationClass : Application() {
   override fun onCreate() {
      super.onCreate()
        
      // Verbose Logging set to help debug issues, remove before releasing your app.
      OneSignal.Debug.logLevel = LogLevel.VERBOSE

      // OneSignal Initialization
      OneSignal.initWithContext(this, ONESIGNAL_APP_ID)

      // requestPermission will show the native Android notification permission prompt.
      // NOTE: It's recommended to use a OneSignal In-App Message to prompt instead.
      CoroutineScope(Dispatchers.IO).launch {
         OneSignal.Notifications.requestPermission(true)
      }
   }
}

import com.onesignal.OneSignal;
import com.onesignal.debug.LogLevel;
import com.onesignal.Continue;

public class ApplicationClass extends Application {
  
    // NOTE: Replace the below with your own ONESIGNAL_APP_ID
    private static final String ONESIGNAL_APP_ID = "########-####-####-####-############";
  
    @Override
    public void onCreate() {
        super.onCreate();
        
        // Verbose Logging set to help debug issues, remove before releasing your app.
        OneSignal.getDebug().setLogLevel(LogLevel.VERBOSE);
        
        // OneSignal Initialization
        OneSignal.initWithContext(this, ONESIGNAL_APP_ID);
      
        // requestPermission will show the native Android notification permission prompt.
        // NOTE: It's recommended to use a OneSignal In-App Message to prompt instead.
        OneSignal.getNotifications().requestPermission(true, Continue.with(r -> {
            if (r.isSuccess()) {
              if (r.getData()) {
                // `requestPermission` completed successfully and the user has accepted permission
              }
              else {
                // `requestPermission` completed successfully but the user has rejected permission
              }
            }
            else {
              // `requestPermission` completed unsuccessfully, check `r.getThrowable()` for more info on the failure reason
            }
        }));
    }
}

3. Customize default icons

3. Customize default icons

By default, notifications will be shown with a small bell icon in the notification shade. Follow the Customize Notification Icons guide to create your own small and large notification icons for your app.

4. Testing

4. Testing

Run your app on a physical device to make sure it builds correctly.

If you used the provided code, then the requestPermission method, should prompt you to subscribe to push notifications. You can change this later.

Check your OneSignal Dashboard Audience > Subscriptions to see your User & Subscription Record.

Then head over to Messages > New Push to Send your first Push Notification from OneSignal.

Please note that Identity Verification is coming soon to v5 of the Android SDK.

📘

Troubleshooting

If running into issues, see our Mobile Troubleshooting Guide.

Try our example projects on our Github repository.

If stuck, or email [email protected] for help.

For faster assistance, please provide:

  • Your OneSignal App ID
  • Details, logs, and/or screenshots of the issue.
  • Steps to reproduce

Recommended

Recommended

Push permission with In-App Message

Push permission with In-App Message

You can continue to opt-in users to push via the requestPermission method. However, Apple's Human Interface Guidelines recommends 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 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 is limited to how many times it can show and cannot be shown again if the user clicks deny.

See How to Prompt for Push Permissions with In-App Messages for details on implementing this.

Identify Users

Identify Users

Required if using integrations.
Recommended for messaging across multiple channels (push, email, sms).

OneSignal creates subscription-level records under a unique ID called the subscription_id. A single user can have multiple subscription_id records based on how many devices, email addresses, and phone numbers they use to interact with your app.

If your app has its own login system to track users, call login at any time to link all channels to a single user. For more details, see Aliases & External ID.

val externalId = "123456789" // You will supply the external user id to the OneSignal SDK
OneSignal.login(externalId)
String externalId = "123456789"; // You will supply the external id to the OneSignal SDK
OneSignal.login(externalId);

Set Email & Phone Number

Set Email & Phone Number

Recommended for messaging across multiple channels (push, email, sms).

Use the provided SDK methods to capture one or more email/phone numbers for the user. Follow the channel quickstart guides for setup:

// Pass in email provided by customer
OneSignal.User.addEmail("[email protected]")

// Pass in phone number provided by customer
OneSignal.User.addSms("+11234567890")
// Pass in email provided by customer
OneSignal.getUser().addEmail("[email protected]");

// Pass in phone number provided by customer
OneSignal.getUser().addSms("+11234567890");

Add Data Tags

Optional

Tags are custom key : value pairs of String data used for tracking user events and properties. Setting tags is required for more complex segmentation and message personalization.

See Data Tags for more details.

OneSignal.User.addTag("key", "value")
OneSignal.getUser().addTag("key", "value");

How do you implement OneSignal?

Android SDK Setup

70

0

Comments

Please Join Us to post.

0/2000

All Comments ( 0 )

Guest Posts

If you are interested in sending in a Guest Blogger Submission,welcome to write for us!

Your Name: (required)

Your Email: (required)

Subject:

Your Message: (required)