Skip to main content
This guide walks you through adding OneSignal to your iOS app using Xcode. You’ll install our SDK, setup push and in-app messages, and send test messages to confirm everything is working. If this is your first time using OneSignal, follow the steps in order. If you’re experienced, feel free to jump to the sections you need.
Using an AI coding assistant? For AI-driven installation, use this prompt:
Integrate the OneSignal iOS SDK into this codebase.

Follow the instructions at:
https://raw.githubusercontent.com/OneSignal/sdk-ai-prompts/main/docs/ios/ai-prompt.md

Step 0. Configure APNs in OneSignal (required to deliver push)

You can install and initialize the OneSignal iOS SDK without completing this step. However, push notifications will not deliver until APNs credentials are configured in your OneSignal app.
If your company already has a OneSignal account, ask to be invited as an admin role to configure the app. Otherwise, sign up for a free account to get started.
These steps connect your OneSignal app to Apple Push Notification service (APNs). You only need to do this once per app.
  1. Login to https://onesignal.com and create or select your App.
  2. Navigate to Settings > Push & In-App to Set up Push & In-App.
  3. Select Apple iOS (APNs) and Continue through the setup wizard.
  4. Input your p8 Auth Key (Recommended) or p12 Certificate details.
  5. Continue through the setup wizard to get your App ID. This will be used to initialize the SDK.
For full setup instructions, see our Mobile push setup guide.

Setup contract & requirements

This section summarizes the tools, versions, and assumptions used throughout the guide.
  • SDK version: 5.4.0+ (latest: check releases)
  • SDK repo: https://github.com/OneSignal/OneSignal-XCFramework
  • Xcode: 16.0+
  • iOS: 12.0+ minimum, 16.2+ recommended
  • Simulator: iOS 16.2+ required for push testing
  • App target packages: OneSignalFramework (required), OneSignalInAppMessages (recommended), OneSignalLocation (optional)
  • Notification Service Extension (NSE) target name: OneSignalNotificationServiceExtension
  • Notification Service Extension (NSE) target package: OneSignalExtension
  • App Group format: group.{bundle_id}.onesignal
  • App ID format: 36-character UUID (example: 12345678-1234-1234-1234-123456789012) — find at OneSignal Dashboard > Settings > Keys & IDs
  • Initialize: OneSignal.initialize("YOUR_APP_ID", withLaunchOptions: launchOptions)
  • Requires NSE + App Group: images, confirmed delivery, badges
  • Confirmed Delivery: Requires an eligible plan (not available on free plans)
  • Recommended: Assign External ID via OneSignal.login("user_id") to unify users across devices

iOS setup steps

By the end of the steps below, you will have:
  • The OneSignal SDK installed and initialized in your iOS app
  • Push notification permissions prompting correctly on a real device
  • A test push and in-app message successfully delivered
If you skipped Step 0 (Configuring APNs in OneSignal), you can still complete the Xcode setup below. Complete Step 0 before you test or send push notifications.

Step 1. Enable Push Notifications and Background Modes

  1. Open your .xcodeproj in Xcode (or .xcworkspace if using CocoaPods)
  2. Select app target > Signing & Capabilities
  3. Click + Capability > add Push Notifications
  4. Click + Capability > add Background Modes
  5. Enable Remote notifications checkbox
Xcode showing the app target with Push Notifications and Background Modes capabilities.

Step 2. Add a Notification Service Extension (NSE)

The NSE enables rich notifications (images) and Confirmed Delivery analytics. Create the target:
  1. File > New > Target…
  2. Select Notification Service Extension > Next
  3. Product name: OneSignalNotificationServiceExtension
  4. Click Finish > click Don’t Activate when prompted
Xcode showing how to createthe Notification Service Extension target.
Xcode showing how to name the Notification Service Extension and use the following options if your app is written in Swift.
Xcode showing how to not activate the NSE Scheme.
Configure the target:
  1. Select OneSignalNotificationServiceExtension target > General
  2. Set Minimum Deployments to match your app target
Xcode showing how to set the OneSignalNotificationServiceExtension Minimum Deployments target to be the same as your main App target.
Xcode showing how to set the App target Minimum Deployments target to be the same as your OneSignalNotificationServiceExtension target.
Update NSE code:
  1. Navigate to OneSignalNotificationServiceExtension/NotificationService.swift
  2. Replace the contents with the code below:
// FILE: OneSignalNotificationServiceExtension/NotificationService.swift
// PURPOSE: Enables rich notifications (images) and confirmed delivery analytics
// REQUIREMENT: This extension must share an App Group with the main app target (configured in next steps)
// WHEN IT RUNS: iOS calls this extension when a push has "mutable-content": true
//               (automatically set when you include images or action buttons)

import UserNotifications
import OneSignalExtension

class NotificationService: UNNotificationServiceExtension {
    
    // Callback to deliver the modified notification to iOS
    var contentHandler: ((UNNotificationContent) -> Void)?
    
    // The original push request from APNs
    var receivedRequest: UNNotificationRequest!
    
    // A mutable copy of the notification we can modify (add images, etc.)
    var bestAttemptContent: UNMutableNotificationContent?

    // Called when a push notification arrives with mutable-content: true
    // You have ~30 seconds to modify the notification before iOS displays it
    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 to verify NSE is running
            // bestAttemptContent.body = "[Modified] " + bestAttemptContent.body

            // OneSignal processes the notification:
            // - Downloads and attaches images
            // - Reports confirmed delivery to dashboard
            // - Handles action buttons
            OneSignalExtension.didReceiveNotificationExtensionRequest(self.receivedRequest, with: bestAttemptContent, withContentHandler: self.contentHandler)
        }
    }

    // Called if didReceive() takes too long (~30 seconds)
    // Delivers whatever content we have so the notification isn't lost
    override func serviceExtensionTimeWillExpire() {
        if let contentHandler = contentHandler, let bestAttemptContent = bestAttemptContent {
            OneSignalExtension.serviceExtensionTimeWillExpireRequest(self.receivedRequest, with: self.bestAttemptContent)
            contentHandler(bestAttemptContent)
        }
    }
}
Don’t panic! Build errors will resolve after installing the SDK.
Xcode showing the updated NSE code with error that will resolve after installing the SDK.

Step 3. Create an App Group

App Groups enable data sharing between your app and the NSE. Required for confirmed delivery, badges, and images.
  1. Select app target > Signing & Capabilities
  2. Click + Capability > add App Groups
  3. Click + and enter: group.{BUNDLE_IDENTIFIER}.onesignal
    • Find your Bundle Identifier at app target > General, or run:
      xcodebuild -showBuildSettings 2>/dev/null | grep PRODUCT_BUNDLE_IDENTIFIER | head -1 | awk '{print "group."$3".onesignal"}'
      
  4. Select OneSignalNotificationServiceExtension target > Signing & Capabilities
  5. Click + Capability > add App Groups
  6. Select the same App Group ID you just created
If you need OneSignal to use an existing App Group instead of creating a new one, add this to Info.plist for both your app target and NSE target. Replace group.your-existing-group-id with your existing App Group ID.
<key>OneSignal_app_groups_key</key>
<string>group.your-existing-group-id</string>
Xcode showing the main app target is part of the group.YOUR_BUNDLE_IDENTIFIER.onesignal App Group.
Xcode showing the OneSignalNotificationServiceExtension target is part of the same group.YOUR_BUNDLE_IDENTIFIER.onesignal App Group.
Xcode showing if you decided to use your own App Group, you must add the OneSignal_app_groups_key to the Info.plist for both the app target and the OneSignalNotificationServiceExtension target.

Step 4. Install the OneSignal SDK

Swift Package Manager (recommended):
  1. Select Your project file > Package Dependencies > +
  2. Enter: https://github.com/OneSignal/OneSignal-XCFramework
  3. Click Add Package
  4. Assign packages:
PackageTargetRequired
OneSignalExtensionOneSignalNotificationServiceExtension
OneSignalFrameworkApp
OneSignalInAppMessagesAppRecommended
OneSignalLocationAppOptional
Xcode showing how to add the onesignal-xcframework package.
Xcode showing the example shows adding the correct packages to the correct targets omitting Location. If you want location tracking, add it to the main app target.
Most common install mistake (SPM): products added to the wrong targetDouble-check product-to-target mapping:
  • App target must include: OneSignalFramework (and optionally OneSignalInAppMessages, OneSignalLocation)
  • OneSignalNotificationServiceExtension target must include: OneSignalExtension
If you see No such module 'OneSignalFramework', it usually means the app target is missing OneSignalFramework. If you see No such module 'OneSignalExtension', it usually means the NSE target is missing OneSignalExtension.
Where to verify in Xcode: select the target → Build Phases → confirm the correct OneSignal products appear under “Link Binary With Libraries”.
Requires CocoaPods 1.16.2+. Add to Podfile:
Podfile
# If platform is uncommented, set to the same value as your minimum deployments target in Xcode
# platform :ios, '15.0'

target 'YourAppName' do
  pod 'OneSignal/OneSignal', '>= 5.2.9', '< 6.0'
  pod 'OneSignal/OneSignalInAppMessages', '>= 5.2.9', '< 6.0'
  pod 'OneSignal/OneSignalLocation', '>= 5.2.9', '< 6.0'  # Optional
end

target 'OneSignalNotificationServiceExtension' do
  pod 'OneSignal/OneSignal', '>= 5.2.9', '< 6.0'
end
Run pod repo update && pod install, then open .xcworkspace (not .xcodeproj).Common error: 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.
  1. Close Xcode.
  2. Navigate to your project’s ios/<your-app>.xcodeproj/project.pbxproj file.
  3. Change this line: objectVersion = 70;
  4. Replace it with: objectVersion = 55;
  5. Save, close, and rerun cd ios pod install cd ..
Verify that the build succeeds without “No such module” errors.

Step 5. Initialize OneSignal

SwiftUI:
Swift
// FILE: {AppName}App.swift
// PURPOSE: Initialize OneSignal when your app launches

import SwiftUI
import OneSignalFramework

@main
struct YourAppNameApp: App {
    // SwiftUI apps don't have an AppDelegate by default
    // This adapter lets us use UIApplicationDelegate methods like didFinishLaunchingWithOptions
    @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate

    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}

class AppDelegate: NSObject, UIApplicationDelegate {
    
    // Called once when the app finishes launching
    // This is the earliest point to initialize SDKs
    func application(_ application: UIApplication,
                     didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil) -> Bool {
        
        // Enable verbose logging to debug issues (remove in production)
        OneSignal.Debug.setLogLevel(.LL_VERBOSE)
        
        // Replace with your 36-character App ID from Dashboard > Settings > Keys & IDs
        OneSignal.initialize("YOUR_APP_ID", withLaunchOptions: launchOptions)
        
        // Prompt user for push notification permission
        // In production, consider using an in-app message instead for better opt-in rates
        // fallbackToSettings: if previously denied, opens iOS Settings to re-enable
        OneSignal.Notifications.requestPermission({ accepted in
            print("User accepted notifications: \(accepted)")
        }, fallbackToSettings: false)
        
        return true
    }
}
// FILE: AppDelegate.swift
// PURPOSE: Initialize OneSignal when your app launches

import UIKit
import OneSignalFramework

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    // Called once when the app finishes launching
    // This is the earliest point to initialize SDKs
    func application(_ application: UIApplication,
                     didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

        // Enable verbose logging to debug issues (remove in production)
        OneSignal.Debug.setLogLevel(.LL_VERBOSE)
        
        // Replace with your 36-character App ID from Dashboard > Settings > Keys & IDs
        OneSignal.initialize("YOUR_APP_ID", withLaunchOptions: launchOptions)

        // Prompt user for push notification permission
        // In production, consider using an in-app message instead for better opt-in rates
        // fallbackToSettings: if previously denied, opens iOS Settings to re-enable
        OneSignal.Notifications.requestPermission({ accepted in
            print("User accepted notifications: \(accepted)")
        }, fallbackToSettings: false)

        return true
    }
}
Verify the app builds, runs, and shows the push permission prompt.

Step 6. Test the integration

Verify subscription:
  1. Launch app on device
  2. Check Dashboard > Audience > Subscriptions — status shows “Never Subscribed”
  3. Accept the permission prompt
  4. Refresh dashboard — status changes to “Subscribed”
Example of the iOS and Android push permission prompts.
Dashboard showing Subscription with 'Never Subscribed' status.
After allowing push permissions, refresh the dashboard to see the Subscription status update to '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.

Create test Subscription and segment

  1. Click next to the Subscription > Add to Test Subscriptions > name it
  2. Go to Audience > Segments > New Segment
  3. Name: Test Users, add filter Test Users > Create Segment
Add a Test Subscription.
Create a 'Test Users' segment with the Test Users filter.
You have successfully created a segment of test users. We can now test sending messages to this individual device and groups of test users.

Send test push via API

  1. Navigate to Settings > Keys & IDs.
  2. In the provided code, replace YOUR_APP_API_KEY and YOUR_APP_ID in the code below with your actual keys. This code uses the Test Users segment we created earlier.
curl -X POST 'https://api.onesignal.com/notifications' \
  -H 'Content-Type: application/json; charset=utf-8' \
  -H 'Authorization: Key YOUR_APP_API_KEY' \
  -d '{
    "app_id": "YOUR_APP_ID",
    "target_channel": "push",
    "name": "Testing basic setup",
    "headings": { "en": "👋" },
    "contents": {"en": "Hello world!"},
    "included_segments": ["Test Users"],
    "ios_attachments": {"onesignal_logo": "https://avatars.githubusercontent.com/u/11823027?s=200&v=4"}
  }'
Images in push notifications appear small in the collapsed notification view. Expand the notification to see the full image.
Delivery stats showing confirmed delivery (unavailable on free plans).
Verify the test device received a notification with:
  • An image.
  • Dashboard > Delivery > Sent Messages shows “Confirmed” status (unavailable on free plans).
  • No image received? Your Notification Service Extension might be missing or incomplete setup.
  • No confirmed delivery? Review the troubleshooting guide here.
  • Having issues? Copy-paste the api request and a log from start to finish of app launch into a .txt file. Then share both with [email protected].

Test in-app messages

  1. Close app for 30+ seconds
  2. Dashboard > Messages > In-App > New In-App > select Welcome template
  3. Audience: Test Users segment
  4. Trigger: On app open
  5. Schedule: Every time trigger conditions are satisfied
  6. Click Make Message Live
  7. Open app
Targeting the 'Test Users' segment with an in-app message.
Example customization of in-app Welcome message.
In-app message scheduling options.
Welcome in-app message shown on devices.
Verify the test device received an in-app message. See the In-app messages setup guide for more details.
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.
    • For more, see how in-app messages are displayed.
  • Still in the Test Users segment?
    • If you reinstalled or switched devices, re-add the device to Test Subscriptions 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 [email protected] and we will help investigate what’s going on.
You have successfully setup the OneSignal SDK and learned important concepts like:Continue with this guide to identify users in your app and setup additional features.

Common Errors & Fixes

Error / SymptomCauseFix
No such module 'OneSignalFramework'Package not added to app targetAdd OneSignalFramework via File > Add Package Dependencies. Clean and build the project.
No such module 'OneSignalExtension'Package not added to NSEAdd OneSignalExtension to OneSignalNotificationServiceExtension target. Clean and build the project.
Push received but no imageNSE not runningVerify NSE deployment target matches app; confirm code is updated
No confirmed delivery statApp Group mismatchApp Group ID must be identical in both targets
Badges not updatingApp Group missingAdd App Groups capability to both targets
In-app not showingSession not started or missing OneSignalInAppMessages frameworkCheck the framework is added, then close app 30+ seconds before reopening
Can’t diagnose issueNot enough log infoAdd OneSignal.Debug.setLogLevel(.LL_VERBOSE) before initialize, then reproduce the issue to get a log

User management

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. 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. See our Mobile SDK reference for more details and Objective-C code examples.
// Call when user logs in or is identified, safe to call multiple times
// Typically used in a login completion handler, or on app launch if already authenticated
func onUserAuthenticated(userId: String) {
    OneSignal.login(userId)
}

// If you want to remove the External ID from the Subscription, setting it to an anonymous user
func onUserLoggedOut() {
    OneSignal.logout()
}
OneSignal generates unique read-only IDs for Subscriptions (Subscription ID) and Users (OneSignal ID).Setting the External ID via our SDK is highly recommended to identify users across all their subscriptions, regardless of how they are created.Learn more about the login method in the SDK reference guide.

Add Tags & Custom Events

Tags and Custom Events are both ways to add data to your users. Tags are key-value strings or numbers and are generally associated with user properties (like username, role, or status) while Custom Events have a JSON format and are usually associated with actions (like new_purchase, abandoned_cart, and associated properties). Both can be used to power advanced Message Personalization and Journeys. See our Mobile SDK reference for more details and Objective-C code examples.
// Add a tag when the user's name is set
OneSignal.User.addTag(key: "username", value: "john_doe")

// Create a custom event when user abandoned a cart
let myProperties = [
  "product_id": "123456",
  "product_name": "Product Name",
  "product_price": 100,
  "product_quantity": 1
]
OneSignal.User.trackEvent(name: "abandoned_cart", properties: myProperties as [String: Any])
More details on how to use Tags and Custom Events in the Tags and Custom Events guides.

Add email and/or SMS subscriptions

You can reach users through email and SMS channels in addition to push notifications. 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. See our Mobile SDK reference for more details and Objective-C code examples.
// Add email subscription
// Call when user provides their email (e.g., account creation, settings update) after calling OneSignal.login("user_id")
OneSignal.User.addEmail("[email protected]")

// Add SMS subscription
// Use E.164 format: + country code + number
// Call when user provides their phone number (e.g., account creation, settings update) after calling OneSignal.login("user_id")
OneSignal.User.addSms("+15551234567")
A user profile with push, email, and SMS subscriptions unified by External ID.
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.

To control when OneSignal collects user data, use the SDK’s consent gating methods. See our Mobile SDK reference for more details and Objective-C code examples.
// In AppDelegate, BEFORE OneSignal.initialize()
// Use this if your app requires GDPR or other privacy consent before data collection
OneSignal.setConsentRequired(true)

// Later, after user grants consent (e.g., taps "I Agree" on your consent screen)
OneSignal.setConsentGiven(true)
See our Privacy & security docs for more on:

Prompt for push permissions

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.

Listen to push, user, and in-app events

Use SDK listeners to react to user actions and state changes. Add these in your AppDelegate after OneSignal.initialize().

Push notification events

Example shows how to use the push click listener. Other push notification events like the foreground lifecycle listener to control how notifications behave in foreground are available in the Mobile SDK Reference.
// The OSNotificationClickListener is used to detect push click events
class AppDelegate: NSObject, UIApplicationDelegate, OSNotificationClickListener {

  // Add the required onClick method for OSNotificationClickListener
  func onClick(event: OSNotificationClickEvent) {
    print("Notification clicked: \(event.jsonRepresentation())")
    let notification = event.notification
    // Access notification data
    let title = notification.title ?? ""
    let additionalData = notification.additionalData // Custom key-value pairs you sent
    // Example: Deep link based on custom data
    if let screenName = additionalData?["screen"] as? String {
        // Navigate to the specified screen
    }
  }

  // Reference the listeners in your AppDelegate
  func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
    // For the OSNotificationClickListener
    OneSignal.Notifications.addClickListener(self)

    return true
  }
}

User state changes

Example shows how to use push subscription observer. Other user state events like the user state observer and notification permission observer are available in the Mobile SDK Reference.
// The OSPushSubscriptionObserver is used to detect push subscription changes (token changes, opt-out, etc.)
class AppDelegate: NSObject, UIApplicationDelegate, OSNotificationPermissionObserver, OSPushSubscriptionObserver {

  // Add the onPushSubscriptionChanged method for OSPushSubscriptionObserver
  func onPushSubscriptionChanged(state: OSPushSubscriptionChangedState) {
    print("Push subscription changed: \(state.jsonRepresentation())")
    print(state.current.optedIn)
    print(state.current.token)
    // This is a good spot to update your UI or analytics
  }

  // Reference the observer in your AppDelegate
  func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
    // For the OSPushSubscriptionObserver
    OneSignal.User.pushSubscription.addObserver(self)

    return true
  }
}

In-app message events

Additional in-app message methods are available in the Mobile SDK Reference.
// The OSInAppMessageClickListener is used to detect in-app message button clicks
class AppDelegate: NSObject, UIApplicationDelegate, OSInAppMessageClickListener {
  // Add the onClick method for OSInAppMessageClickListener
  func onClick(event: OSInAppMessageClickEvent) {
    let result: OSInAppMessageClickResult = event.result
    print("In-app message clicked: \(result.jsonRepresentation())")
    let actionId = result.actionId
    print("Action ID: \(actionId ?? "no actionId")")
    // Example: Deep link based on the actionId
    if let screenName = actionId {
        // Navigate to the specified screen
    }
  }

  // Reference the listeners in your AppDelegate
  func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
    // For the OSInAppMessageClickListener
    OneSignal.InAppMessages.addClickListener(self)

    return true
  }
}

Advanced setup & capabilities

For full SDK method documentation, visit the Mobile SDK Reference.
Need help?Chat with our Support team or email [email protected]Please include:
  • Details of the issue you’re experiencing and steps to reproduce if available
  • Your OneSignal App ID
  • The External ID or Subscription ID if applicable
  • The URL to the message you tested in the OneSignal Dashboard if applicable
  • Any relevant logs or error messages
We’re happy to help!