iOS push notifications are essential for driving sustained user engagement and retention in your iOS app. They empower you to deliver real-time updates, reminders, and personalized messages directly to your users, improving the overall user experience and stickiness of your app. By integrating OneSignal’s SDK with your app, you can take advantage of Apple Push Notification Service (APNS) to ensure your notifications are delivered seamlessly across iOS devices. This guide will walk you through integrating our SDK into your iOS app.
Créez une nouvelle application en cliquant sur New App/Website, ou ajoutez une plateforme à une application existante dans Settings > Push & In-App. Sélectionnez la ou les plateformes que vous souhaitez configurer et cliquez sur Next: Configure Your Platform.
Cliquez sur Save & Continue après avoir saisi vos identifiants.
3
Enregistrer votre App ID et installer le SDK
Votre App ID est affiché sur l’écran final. Copiez et enregistrez-le — vous en avez besoin lors de l’initialisation du SDK. Sélectionnez votre plateforme SDK, puis suivez le guide de configuration.
Go to OneSignalNotificationServiceExtension > Signing & Capabilities
Add App Groups
Add the exact same group ID
If you are using a custom App Group name and not group.your_bundle_id.onesignal then make sure to add your App Group ID to both the App Target and OneSignalNotificationServiceExtension Target’s Info.plist! See step 3 for more information.
Navigate to the OneSignalNotificationServiceExtension folder
Replace the contents of the NotificationService.swift or NotificationService.m file with the following:
import UserNotificationsimport OneSignalExtensionclass NotificationService: UNNotificationServiceExtension { var contentHandler: ((UNNotificationContent) -> Void)? var receivedRequest: UNNotificationRequest! var bestAttemptContent: UNMutableNotificationContent? // Note this extension only runs when `mutable_content` is set // Setting an attachment or action buttons automatically sets the property to true 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// print("Running NotificationServiceExtension")// bestAttemptContent.body = "[Modified] " + bestAttemptContent.body OneSignalExtension.didReceiveNotificationExtensionRequest(self.receivedRequest, with: bestAttemptContent, withContentHandler: self.contentHandler) } } override func serviceExtensionTimeWillExpire() { // 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// Note, this extension only runs when mutable-content is set// Setting an attachment or action buttons automatically adds this- (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// NSLog(@"Running NotificationServiceExtension");// self.bestAttemptContent.body = [@"[Modified] " stringByAppendingString:self.bestAttemptContent.body]; [OneSignalExtension didReceiveNotificationExtensionRequest:self.receivedRequest withMutableNotificationContent:self.bestAttemptContent withContentHandler:self.contentHandler];}- (void)serviceExtensionTimeWillExpire { // 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
You should see an error because the OneSignal package is not installed. This will be resolved in the next step.
This section will guide you through integrating OneSignal’s core features. By the end of this section, you will have a basic integration with our SDK enabling you to trigger in-app messages and receive push notifications.
Add our SDK using Xcode Package Dependencies Manager (Swift Package Manager) or CocoaPods. There are 4 available libraries. If you do not want In-app messages and/or Location tracking, you can omit these packages.
Library
Target
Required
OneSignalExtension
OneSignalNotificationServiceExtension
✅
OneSignalFramework
App
✅
OneSignalInAppMessages
App
Recommended
OneSignalLocation
App
Optional
Xcode Package Dependencies
CocoaPods
Navigate to File > Add Package Dependencies… and enter the URL to the OneSignal SDK repository:https://github.com/OneSignal/OneSignal-XCFrameworkSelect the onesignal-xcframework package and click Add Package.Choose Package Products for OneSignal-XCFramework.
Important: Add the OneSignalExtension to the OneSignalNotificationServiceExtension Target.
Add the OneSignalFramework to your App Target.
If you plan on using in-app messages (recommended) and/or location tracking, then add those packages to your App Target as well.
Requirements: CocoaPods 1.16.2+ (Setup instructions use CocoaPods 1.16.2).Open your Podfile and add the following:
Podfile
# If platform is uncommented, set to the same value as your minimum deployment target in Xcode # platform :ios, '15.0' target 'your_project_name' do pod 'OneSignal/OneSignal', '>= 5.2.9', '< 6.0' # If your app does not use In-App messages, you can remove this: pod 'OneSignal/OneSignalInAppMessages', '>= 5.2.9', '< 6.0' # If your app does not use CoreLocation, you can remove this: pod 'OneSignal/OneSignalLocation', '>= 5.2.9', '< 6.0' # Your other pods here end target 'OneSignalNotificationServiceExtension' do pod 'OneSignal/OneSignal', '>= 5.2.9', '< 6.0' end
Add the dependencies to your main app target and OneSignalNotificationServiceExtension target. If platform is uncommented, make sure it is the same value as the minimum deployment target in Xcode.Run the following command to pull down the OneSignal iOS SDK pod and add it to your project:pod repo update && pod installOnce the installation is complete, make sure to open the XCWorkspace file named after your project (e.g., <project-name>.xcworkspace)
When using the OneSignal iOS SDK pod, you must exclusively use the .xcworkspace file to open the project.
You may run into the following errors, here is how you can resolve them.
ArgumentError - \[Xcodeproj] Unable to find compatibility version string for
object version `70`.
CocoaPods relies on the xcodeproj Ruby gem to read your Xcode project files. As of now, the latest xcodeproj release does not recognize object version 70, which was introduced by Xcode 16. So when CocoaPods tries to open your .xcodeproj file, it crashes with this error.
Close Xcode.
Navigate to your project’s ios/<your-app>.xcodeproj/project.pbxproj file.
Depending on your Xcode interface setup, initialize OneSignal following these options.
SwiftUI
Storyboard
If using SwiftUI interface, navigate to your <APP_NAME>App.swift file and initialize OneSignal with the provided methods.Replace YOUR_APP_ID with your OneSignal App ID found in your OneSignal dashboard Settings > Keys & IDs. If you don’t have access to the OneSignal app, ask your Team Members to invite you.
import SwiftUIimport OneSignalFramework@mainstruct YOURAPP_NAME: App { //Connect the SwiftUI app to the UIKit app delegate @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 { // Enable verbose logging for debugging (remove in production) OneSignal.Debug.setLogLevel(.LL_VERBOSE) // Initialize with your OneSignal App ID OneSignal.initialize("YOUR_APP_ID", withLaunchOptions: launchOptions) // Use this method to prompt for push notifications. // We recommend removing this method after testing and instead use In-App Messages to prompt for notification permission. OneSignal.Notifications.requestPermission({ accepted in print("User accepted notifications: \(accepted)") }, fallbackToSettings: false) return true }}
If using Storyboard interface, navigate to your AppDelegate file and initialize OneSignal with the provided methods.Replace YOUR_APP_ID with your OneSignal App ID found in your OneSignal dashboard Settings > Keys & IDs. If you don’t have access to the OneSignal app, ask your Team Members to invite you.
//AppDelegate.swiftimport UIKitimport OneSignalFramework@UIApplicationMainclass AppDelegate: UIResponder, UIApplicationDelegate {func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions:[UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Enable verbose logging for debugging (remove in production) OneSignal.Debug.setLogLevel(.LL_VERBOSE) // Initialize with your OneSignal App ID OneSignal.initialize("YOUR_APP_ID", withLaunchOptions: launchOptions) // Use this method to prompt for push notifications. // We recommend removing this method after testing and instead use In-App Messages to prompt for notification permission. OneSignal.Notifications.requestPermission({ accepted in print("User accepted notifications: \(accepted)") }, fallbackToSettings: false) return true}// Remaining contents of your AppDelegate Class...}
#import <OneSignalFramework/OneSignalFramework.h>@implementation AppDelegate- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { // Enable verbose logging for debugging (remove in production) [OneSignal.Debug setLogLevel:ONE_S_LL_VERBOSE]; // Initialize with your OneSignal App ID [OneSignal initialize:@"YOUR_APP_ID" withLaunchOptions:launchOptions]; // Use this method to prompt for push notifications. // We recommend removing this method after testing and instead use In-App Messages to prompt for notification permission. [OneSignal.Notifications requestPermission:^(BOOL accepted) { NSLog(@"User accepted notifications: %d", accepted); } fallbackToSettings:false]; // Login your customer with externalId // [OneSignal login:@"EXTERNAL_ID"]; return YES;}
This guide helps you verify that your OneSignal SDK integration is working correctly by testing push notifications, subscription registration, and in-app messaging.
The native push permission prompt should appear automatically if you added the requestPermission method during initialization.
2
Check your OneSignal dashboard
Before accepting the prompt, check the OneSignal dashboard:
Go to Audience > Subscriptions.
You should see a new entry with the status “Never Subscribed”.
3
Return to the app and tap Allow on the prompt.
4
Refresh the OneSignal dashboard Subscription's page.
The subscription’s status should now show Subscribed.
You have successfully created a mobile subscription.
Mobile subscriptions are created when users first open your app on a device or if they uninstall and reinstall your app on the same device.
If all setup steps were completed successfully, the test users should receive a notification with an image included:
Images will appear small in the collapsed notification view. Expand the notification to see the full image.
5
Check for confirmed receipt.
In your dashboard, go to Delivery > Sent Messages, then click the message to view stats.You should see the confirmed stat, meaning the device received the push.
You have successfully sent a notification via our API to a segment.
In-app messages let you communicate with users while they are using your app.
1
Close or background your app on the device.
This is because users must meet the in-app audience criteria before a new session starts. In OneSignal, a new session starts when the user opens your app after it has been in the background or closed for at least 30 seconds. For more details, see our guide on how in-app messages are displayed.
2
Create an in-app message.
In your OneSignal dashboard, navigate to Messages > In-App > New In-App.
Find and select the Welcome message.
Set your Audience as the Test Users segment we used previously.
3
Customize the message content if desired.
4
Set Trigger to 'On app open'.
5
Schedule frequency.
Under Schedule > How often do you want to show this message? select Every time trigger conditions are satisfied.
6
Make message live.
Click Make Message Live so it is available to your Test Users each time they open the app.
7
Open the app and see the message.
After the in-app message is live, open your app. You should see it display:
Not seeing the message?
Start a new session
You must close or background the app for at least 30 seconds before reopening. This ensures a new session is started.
If you reinstalled or switched devices, re-add the device to Test Users and confirm it’s part of the Test Users segment.
Having issues?
Follow Getting a Debug Log while reproducing the steps above. This will generate additional logging that you can share with support@onesignal.com and we will help investigate what’s going on.
You have successfully setup the OneSignal SDK and learned important concepts like:
Previously, we demonstrated how to create mobile Subscriptions. Now we’ll expand to identifying Users across all their subscriptions (including push, email, and SMS) using the OneSignal SDK. We’ll cover External IDs, tags, multi-channel subscriptions, privacy, and event tracking to help you unify and engage users across platforms.
Use an External ID to identify users consistently across devices, email addresses, and phone numbers using your backend’s user identifier. This ensures your messaging stays unified across channels and 3rd party systems (especially important for Integrations).Set the External ID with our SDK’s login method each time they are identified by your app.
OneSignal generates unique read-only IDs for subscriptions (Subscription ID) and users (OneSignal ID).As users download your app on different devices, subscribe to your website, and/or provide you email addresses and phone numbers outside of your app, new subscriptions will be created.Setting the External ID via our SDK is highly recommended to identify users across all their subscriptions, regardless of how they are created.
Tags are key-value pairs of string data you can use to store user properties (like username, role, or preferences) and events (like purchase_date, game_level, or user interactions). Tags power advanced Message Personalization and Segmentation allowing for more advanced use cases.Set tags with our SDK addTag and addTags methods as events occur in your app.In this example, the user reached level 6 identifiable by the tag called current_level set to a value of 6.
We can create a segment of users that have a level of between 5 and 10, and use that to send targeted and personalized messages:
Earlier we saw how our SDK creates mobile subscriptions to send push and in-app messages. You can also reach users through emails and SMS channels by creating the corresponding subscriptions.
If the email address and/or phone number already exist in the OneSignal app, the SDK will add it to the existing user, it will not create duplicates.You can view unified users via Audience > Users in the dashboard or with the View user API.
Best practices for multi-channel communication
Obtain explicit consent before adding email or SMS subscriptions.
Explain the benefits of each communication channel to users.
Provide channel preferences so users can select which channels they prefer.
Instead of calling requestPermission() immediately on app open, take a more strategic approach. Use an in-app message to explain the value of push notifications before requesting permission.For best practices and implementation details, see our Prompt for push permissions guide.
Use SDK listeners to react to user actions and state changes.The SDK provides several event listeners for you to hook into. See our SDK reference guide for more details.
Par défaut, le SDK OneSignal utilise le method swizzling pour gérer automatiquement les méthodes de délégué de notification push. Si votre application doit désactiver le swizzling (par exemple, pour éviter les conflits avec d’autres SDKs ou pour maintenir un contrôle total sur les méthodes de délégué de notification), vous pouvez le désactiver via Info.plist.Lorsque le swizzling est désactivé, vous devez transférer manuellement les méthodes de délégué de notification au SDK OneSignal. Toutes les autres fonctionnalités du SDK (listeners, observers, messages in-app, outcomes, etc.) continuent de fonctionner normalement.
Ajoutez ce qui suit au Info.plist de votre application :
<key>OneSignal_disable_swizzling</key><true/>
Lorsque le SDK détecte ce flag, il ignore tout le method swizzling au démarrage et enregistre un avertissement vous rappelant d’implémenter le transfert manuel.
Étape 2. Définir le délégué UNUserNotificationCenter
Définissez votre AppDelegate comme délégué de UNUserNotificationCenteravant d’appeler OneSignal.initialize. Sans cela, l’affichage des notifications au premier plan et la gestion des appuis sur les notifications ne fonctionneront pas.
// In application(_:didFinishLaunchingWithOptions:), BEFORE OneSignal.initialize()UNUserNotificationCenter.current().delegate = self
// In application:didFinishLaunchingWithOptions:, BEFORE [OneSignal initialize:][UNUserNotificationCenter currentNotificationCenter].delegate = self;
Affichage des notifications au premier plan :Le SDK appelle votre completion block avec un objet OSNotification. S’il est non-nil, le SDK souhaite que la notification soit affichée — passez vos options de présentation préférées. S’il est nil (p.ex., un aperçu IAM), ne passez aucune option de présentation.
Le listener de cycle de vie onWillDisplayNotification et les APIs preventDefault / display continuent de fonctionner avec le transfert manuel. Le SDK invoque vos listeners depuis handleWillPresentNotificationInForegroundWithPayload.
Lorsque le swizzling est désactivé, le SDK ne peut pas intercepter les changements de badge. Utilisez cette méthode pour définir le nombre de badges et garder le cache de badges interne d’OneSignal synchronisé :
Les applications SwiftUI n’ont pas de AppDelegate par défaut. Utilisez @UIApplicationDelegateAdaptor pour en ajouter un, puis implémentez toutes les méthodes de transfert présentées ci-dessus :
Swift
@mainstruct YourApp: App { @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate var body: some Scene { WindowGroup { ContentView() } }}class AppDelegate: NSObject, UIApplicationDelegate, UNUserNotificationCenterDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil) -> Bool { UNUserNotificationCenter.current().delegate = self OneSignal.initialize("YOUR_APP_ID", withLaunchOptions: launchOptions) return true } // Implement all the forwarding methods shown above}
Make sure you’ve enabled all key features by reviewing the Mobile push setup guide.For full details on available methods and configuration options, visit the Mobile SDK reference.
Congratulations! You’ve successfully completed the Mobile SDK setup guide.
Besoin d’aide ?Discutez avec notre équipe d’assistance ou envoyez un e-mail à support@onesignal.comVeuillez inclure :
Les détails du problème que vous rencontrez et les étapes de reproduction si disponibles
Votre OneSignal App ID
L’External ID ou le Subscription ID le cas échéant
L’URL du message que vous avez testé dans le OneSignal Dashboard le cas échéant