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    Support

iOS SDK Setup

For Developers

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 Open the Xcode project settings and select the OneSignalNotificationServiceExtension target. 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.


2. Import OneSignal into your Xcode project

Setup CocoaPods on your system if you don't have it already.

  • Make sure you have version 1.1.0 or newer by running pod --version from the terminal.
  • Run the following to upgrade sudo gem install cocoapods

2.1 Make sure your current Xcode project is closed.
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 pod 'OneSignal', '>= 2.5.2', '< 3.0' in your project name target as well as OneSignalNotificationServiceExtension.

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

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

2.5 Run the following from the terminal.

pod repo update
pod install

2.6 Open the newly created .xcworkspace file.
Make sure to always open the workspace from now on.
2.7 Continue to Steps 3 and 4 below

Alternatively follow our Carthage setup guide instead if you can't use Cocoapods in your project.


3. Add Required Capabilities

3.1 Select the root project and Under Capabilities Enable "Push Notifications".
3.2 Next Enable "Background Modes" and check "Remote notifications".


4. Add Required Code

Add following OneSignal initialization code to your AppDelegate.

import OneSignal

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

   let onesignalInitSettings = [kOSSettingsKeyAutoPrompt: false]
        
   // Replace 'YOUR_APP_ID' with your OneSignal App ID.
   OneSignal.initWithLaunchOptions(launchOptions,
       appId: "YOUR_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)")
   })
      
   return true
}
#import <OneSignal/OneSignal.h>

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
   // Replace '11111111-2222-3333-4444-0123456789ab' with your OneSignal App ID.
   [OneSignal initWithLaunchOptions:launchOptions
                              appId:@"11111111-2222-3333-4444-0123456789ab"
   				 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);
   }];
    
   return YES;
}

Note that OneSignal initWithLaunchOptions must be called from your didFinishLaunchingWithOptions, as in the example above.

Troubleshooting

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


5. Add Email

Recommended

Next, if you collect emails from users, you can set a user's email with the setEmail method. This enables OneSignal Email Messaging, which allows you to send emails in addition to push.

OneSignal.setEmail("example@domain.com");
[OneSignal setEmail:@"example@domain.com"];

If you have a backend server, we strongly recommend using Identity Verification with your users. Your backend can generate an email authentication token and send it to your app or website. The following code also includes callbacks:

let emailAuthHash = //generated on your backend server
let email = "example@domain.com";
OneSignal.setEmail(email, withEmailAuthHashToken: emailAuthHash, withSuccess: {
    //The email has successfully been set.
}) { (error) in
    //Encountered an error while setting the email.
};
NSString *hashToken = //hash token from your server
NSString *emailAddress = @"example@domain.com";
[OneSignal setEmail:emailAddress withEmailAuthHashToken:hashToken onSuccess: ^() {
    //The email has successfully been set.
} onFailure: ^(NSError *error) {
    //Encountered an error while setting the email.
}];

Additional email methods are available in the iOS Native SDK.

6. Add App Groups (Optional but 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


Notification Features

To configure notifications features, go to Features Setup.

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.

iOS SDK Setup

For Developers