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

iOS SDK Setup

Instructions for adding the OneSignal SDK to your iOS native app with Swift or Objective-C

Required For Setup

1. Add Notification Service Extension

1.1 In Xcode Select File > New > Target...
1.2 Select Notification Service Extension then press Next.

1.3 Enter the product name as OneSignalNotificationServiceExtension and press Finish.

1.4 Press Cancel on the Activate scheme prompt.

By cancelling, 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).

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

1.6 Open NotificationService.m or NotificationService.swift and replace the whole file contents with the below code.

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)
        }
    }
    
}
#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

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

Coming from iOS SDK App Groups setup Guide?

Do not continue with step 2 on this page. Go back to the App Groups guide and continue with Enable "App Groups" Capability


2. Import OneSignal into your Xcode project

We recommend and will setup using CocoaPods as you continue. Alternatively follow our Carthage setup guide instead if you can't use Cocoapods in your project.

2.1 Make sure your current Xcode project is closed and in the project root, run sudo gem install cocoapods
2.2 Run pod init from the terminal in your project directory.
2.3 Open the newly created Podfile with your favorite code editor such as Sublime.
2.4 Add the OneSignal dependency under your project name target as well as OneSignalNotificationServiceExtension target like below.

target 'project_name' do
  pod 'OneSignal', '>= 2.11.2', '< 3.0'
end

target 'OneSignalNotificationServiceExtension' do
  pod 'OneSignal', '>= 2.11.2', '< 3.0'
end

2.5 Run the following from the terminal.

pod repo update
pod install

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


3. Add Required Capabilities

Only do this for the main application target.
Do not do this for the Notification Service Extension.

3.1 Select the root project, your main app target and "Signing & Capabilities"
3.2 Under "Background Modes" check "Remote notifications". You should see Push Notifications already provided.

3.3 If you do not see Push Notifications enabled, click "+ Capability" and double click "Push Notifications" to add it.


4. Add Required Code

Navigate to the AppDelegate file and add the following OneSignal initialization code to didFinishLaunchingWithOptions. Replace YOUR_APP_ID with your OneSignal App ID.

//START OneSignal initialization code
let onesignalInitSettings = [kOSSettingsKeyAutoPrompt: false]

// Replace 'YOUR_APP_ID' with your OneSignal App ID.
OneSignal.initWithLaunchOptions(launchOptions,
appId: "YOUR_ONESIGNAL_APP_ID",
handleNotificationAction: nil,
settings: onesignalInitSettings)

OneSignal.inFocusDisplayType = OSNotificationDisplayType.notification;

// Recommend moving the below line to prompt for push after informing the user about
//   how your app will use them.
OneSignal.promptForPushNotifications(userResponse: { accepted in
print("User accepted notifications: \(accepted)")
})
//END OneSignal initializataion code
[OneSignal initWithLaunchOptions:launchOptions
 appId:@"YOUR_ONESIGNAL_APP_ID"
 handleNotificationAction:nil
 settings:@{kOSSettingsKeyAutoPrompt: @false}];
OneSignal.inFocusDisplayType = OSNotificationDisplayTypeNotification;

// Recommend moving the below line to prompt for push after informing the user about
// how your app will use them.
[OneSignal promptForPushNotificationsWithUserResponse:^(BOOL accepted) {
  NSLog(@"User accepted notifications: %d", accepted);
}];

Make sure to import the OneSignal headers:

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

Your AppDelegate file should now look like this:

import OneSignal

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: 
[UIApplicationLaunchOptionsKey: Any]?) -> Bool {
  // Insert OneSignal initialization code from above here
  //START OneSignal initialization code
  let onesignalInitSettings = [kOSSettingsKeyAutoPrompt: false]

  // Replace 'YOUR_APP_ID' with your OneSignal App ID.
  OneSignal.initWithLaunchOptions(launchOptions,
  appId: "YOUR_ONESIGNAL_APP_ID",
  handleNotificationAction: nil,
  settings: onesignalInitSettings)

  OneSignal.inFocusDisplayType = OSNotificationDisplayType.notification;

  // Recommend moving the below line to prompt for push after informing the user about
  //   how your app will use them.
  OneSignal.promptForPushNotifications(userResponse: { accepted in
  print("User accepted notifications: \(accepted)")
  })
  //END OneSignal initializataion code
   return true
}
#import <OneSignal/OneSignal.h>

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
   // Insert OneSignal initialization code from above here
   return YES;
}

Build your project

Make sure you test on an actual iOS device. The simulator does not support push notifications.

Troubleshooting

If run into any issues please see our iOS troubleshooting guide, or our general Troubleshooting section.


5. Add App Groups (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.

You're Done!

Next up: Send your first push notification via the OneSignal Dashboard


Callbacks

OSHandleNotificationReceivedBlock - Called when a notification is received while your app is in focus only.
OSHandleNotificationActionBlock - This will be called when a notification is tapped on.
See our initWithLaunchOptions documentation to add these.

Updated 2 months ago


iOS SDK Setup


Instructions for adding the OneSignal SDK to your iOS native app with Swift or Objective-C

Suggested Edits are limited on API Reference Pages

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