Skip to main content

iOS SDK Setup

Integrate Push Notifications into your native iOS app (UIKit, SwiftUI, or Objective-C) to receive and handle push notifications via APNs.


Beta Release

v1.0.6-beta. Not for production use. APIs may change without notice. Pin the exact version.

Essential Setup
  • Make sure to configure the App ID properly. For additional information see Getting started
  • Configure your push credentials in the AppsOnAir console under App Settings → Push Notifications — upload your APNs Auth Key (.p8) before sending any notifications.

Requirements​

Minimum
iOS15.0
Xcode16+
Swift6.2 (SPM) · 5.9 (CocoaPods)
Objective-CFully supported via AOAPush* facade classes
note

A real device is required to receive APNs tokens. The SDK emits a mock token on Simulator so your registration flow is still testable.

Basic Push vs Advanced Push (Rich Notifications)

Basic push — Steps 1–5 only. No extension targets needed:

  • Text notifications with title and body
  • Tap-to-open and deep links
  • Foreground display control
  • User targeting, tags, segments, opt-in / opt-out

Advanced push — requires optional extension targets. Skip these if you only need basic push:

FeatureAdditional setup
Images in notificationsNotification Service Extension (NSE)
Badge auto-incrementNSE + App Group
Delivered analyticsNSE + App Group
Custom long-press viewNSE + Notification Content Extension (NCE)
Silent push (background data, no alert)Background Modes → Remote notifications (Step 1). No extension needed. See Silent Push

Step 1: Apple Capabilities​

Push notifications on iOS require two capabilities on the main app target. Without them, the device will not register with APNs and no tokens will be generated.

In Xcode, select your app target → Signing & Capabilities:

  1. Add Push Notifications — required for APNs registration and push delivery.
  2. Add Background Modes → enable Remote notifications — required for silent pushes and background delivery.
Additional capabilities for the extensions
TargetCapabilities
Main appPush Notifications, Background Modes → Remote notifications, App Groups (if you use the NSE)
Notification Service Extension (NSE)App Groups (same group as the main app)
Notification Content Extension (NCE)None

See Notification Service Extension and Notification Content Extension.

Notification icon on iOS

iOS always shows your app icon on notifications. APNs has no field for a custom notification icon, so there's nothing to configure (the same applies to OneSignal). To change it, update the app icon in Assets.xcassets and ship a new build.


Step 2: Add the SDK​

The SDK is distributed as three separate products so you only link what each target needs.

  1. In Xcode: File > Add Package Dependencies...
  2. Paste the repository URL and resolve.
  3. Link the correct products to each target:
ProductLink to
AppsOnAir-AppPushMain app target
AppsOnAir-AppPush-ServiceExtNotification Service Extension target only
AppsOnAir-AppPush-ContentExtNotification Content Extension target only

Step 3: Configure Info.plist​

The AppsonairAppId key is already covered in Getting Started — ensure it is present in your Info.plist before continuing.

If you use the Notification Service Extension, the main app and NSE must share an App Group. See NSE Step 3 for the App Group and AppsOnAirAppGroup key.


Step 4: Initialize the SDK​

Call initialize() inside application(_:didFinishLaunchingWithOptions:) so the SDK registers with APNs before any scene connects.

AppDelegate.swift
import UIKit
import AppsOnAir_AppPush

@main
class AppDelegate: UIResponder, UIApplicationDelegate {

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

// Optional: verbose logging before initialize (dev builds only)
AppPushService.Debug.logLevel = .verbose

// Register background sync handlers. Must be called before any scene connects.
AppsOnAirBackgroundSync.registerHandlers()

AppPushService.initialize(debug: true)
AppPushService.setListener(self)
AppPushService.Notifications.requestPermission()
AppsOnAirBackgroundSync.scheduleIfNeeded()

return true
}
}

// MARK: - PushListener
extension AppDelegate: PushListener {

func onAPNsTokenUpdated(token: String, environment: APNsEnvironment) {
// APNs token registered or refreshed — SDK handles registration automatically
}

func onNotificationReceived(notification: PushNotification) {
// Notification received while app is in foreground
}

func onNotificationOpened(notification: PushNotification) {
// User tapped the notification
}

func onError(_ error: PushError) {
// Handle SDK error
}
}
No push code needed in the AppDelegate

The SDK hooks the APNs token and notification delegate methods automatically. This also works when another library owns UNUserNotificationCenter.current().delegate (for example Notifee, a Flutter plugin, or your own delegate): AppsOnAir pushes still reach the SDK and the other delegate keeps receiving its own notifications.


Step 5: Background Sync (Info.plist)​

Background sync lets the SDK silently fetch updates while your app is not in the foreground. Add the task identifier to Info.plist so iOS grants permission to run background tasks.

Info.plist
<key>BGTaskSchedulerPermittedIdentifiers</key>
<array>
<string>com.appsonair.push.background-sync</string>
</array>

Feature Guides​

Observers​

React to subscription state changes and login/logout events without polling.

Observers
// Observe opt-in / token changes
AppPushService.User.pushSubscription.addObserver(self)

func onPushSubscriptionDidChange(state: PushSubscriptionChangedState) {
print("optedIn:", state.current.optedIn)
}

// Observe login / logout
AppPushService.User.addObserver(self)

func onUserStateDidChange(state: UserChangedState) {
print(state.current.externalId ?? "anonymous")
}

Permission​

Request and observe the notification permission.

Permission
// Check current status (synchronous)
let granted = AppPushService.Notifications.permission
let canRequest = AppPushService.Notifications.canRequestPermission

if !granted && canRequest {
AppPushService.Notifications.requestPermission()
}

// Permanently denied → open Settings:
AppPushService.Notifications.requestPermission(fallbackToSettings: true)

// Observe permission changes
AppPushService.Notifications.addPermissionObserver(self)

func onNotificationPermissionDidChange(permission: Bool) {
print("permission granted:", permission)
}

User Identity​

Associate a known user ID with the device after login so you can target push notifications to specific users from the portal.

Login / Logout
AppPushService.login("user_12345")   // call when your user signs in
AppPushService.logout() // call on sign-out — clears tags and aliases

Tags & Segmentation​

Tags are key-value pairs you attach to a device to enable audience segmentation.

Tags
AppPushService.User.addTag(key: "plan", value: "premium")
AppPushService.User.addTags(["plan": "premium", "region": "us-east"])
AppPushService.User.removeTag("plan")
AppPushService.User.removeTags(["plan", "region"])

// Read from local cache (synchronous)
let cached = AppPushService.User.getTags()

// Fetch fresh copy from backend (async)
AppPushService.User.getTags { tags in
print(tags)
}

Language​

Override the device locale for this user. Uses ISO 639-1 codes ("en", "fr", "de").

Language
AppPushService.User.setLanguage("fr")
let lang = AppPushService.User.language

Aliases & Email​

Map this device to an ID in an external system (CRM, helpdesk, analytics) and associate an email address. Each subscription keeps one email, so calling addEmail again replaces the previous address.

Aliases & Email
AppPushService.User.addAlias(label: "crm_id", id: "CRM-9876")
AppPushService.User.addAliases(["crm_id": "CRM-9876", "hubspot_id": "HS-42"])
AppPushService.User.removeAlias("crm_id")

AppPushService.User.addEmail("[email protected]")
AppPushService.User.removeEmail("[email protected]")

Opt-in / Opt-out​

Let users stop receiving push notifications without revoking the OS-level APNs permission.

Push Subscription
// Stop delivery (preserves APNs token)
AppPushService.User.pushSubscription.optOut()

// Resume delivery
AppPushService.User.pushSubscription.optIn()

// Read state
let isOptedIn = AppPushService.User.pushSubscription.optedIn

Foreground Display​

By default the SDK shows banners even when the app is in the foreground. Add a lifecycle listener to intercept and suppress any notification.

Foreground Display
AppPushService.Notifications.addForegroundLifecycleListener(self)

func onWillDisplay(event: NotificationWillDisplayEvent) {
// Call preventDefault() to suppress the banner; omit to show it normally
event.preventDefault()
}

Click / Open Listener​

Fired when the user taps a notification or one of its action buttons.

Click Listener
AppPushService.Notifications.addClickListener(self)

func onClick(event: NotificationClickEvent) {
print(event.result.actionId ?? "body tap")
print(event.result.url ?? "")
}

Badge Count (Optional)​

Manually control the notification badge count on the app icon.

Badge
AppPushService.setBadgeCount(5)
AppPushService.incrementBadgeCount(by: 1)
AppPushService.clearBadgeCount()

// Auto-clear when app comes to foreground (default = true)
AppPushService.autoClearBadgeOnForeground = false // switch to count-down mode

Silent Push (Optional)​

A silent push delivers data to your app without showing a notification. iOS wakes the app in the background so it can run lightweight work, such as a content sync. The push still counts as delivered in analytics.

Requirements:

  • Background Modes → Remote notifications enabled (Step 1).
  • The payload has aps.content-available: 1 and no alert, sound, or badge.
  • Notification permission is not needed. Silent pushes reach devices that declined it.

Set the handler before initialize(), and call completion when your work finishes. iOS gives you about 30 seconds.

Silent Push
AppPushService.onSilentPushReceived = { userInfo, completion in
// run lightweight background work (≤ 30 s)
let syncType = userInfo["sync_type"] as? String
completion(.newData) // or .noData / .failed
}

The SDK hooks application(_:didReceiveRemoteNotification:fetchCompletionHandler:) for you. If your AppDelegate already implements that method, the SDK calls yours instead, so forward the push to the SDK from it:

AppDelegate.swift
func application(_ application: UIApplication,
didReceiveRemoteNotification userInfo: [AnyHashable: Any],
fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
AppPushService.handleSilentPush(userInfo, fetchCompletionHandler: completionHandler)
}
APNs Silent Payload
{
"aps": { "content-available": 1 },
"notification_id": "notif-sync-001",
"sync_type": "orders"
}

To send a silent push from your backend, see REST API → Silent Notifications.

note

iOS throttles silent pushes. Low Power Mode, a disabled Background App Refresh, or an app swiped away from the App Switcher stop delivery entirely. See When Notifications Won't Be Delivered.


Remove Notifications (Optional)​

Remove delivered notifications from the notification centre.

Remove Notifications
AppPushService.Notifications.clearAllNotifications()
AppPushService.Notifications.removeNotification(withIdentifier: "abc")
AppPushService.Notifications.removeNotifications(withIdentifiers: ["a", "b"])

Notification Service Extension (Optional — Rich Push)​

Basic push works without the NSE

Steps 1–5 are all you need for basic push notifications — text, tap-to-open, and deep links. The NSE and NCE are optional extensions you add only when you need:

FeatureRequires
Images in notificationsNSE
Badge auto-incrementNSE + App Group
Delivered analyticsNSE + App Group
Custom expanded view (long-press)NSE + NCE

The Notification Service Extension (NSE) runs in its own process before iOS displays a notification. With the AppsOnAir NSE in place, the SDK:

  • downloads and attaches an image, video or audio file (up to 3 attachments; the first one appears in the banner)
  • applies the title, subtitle, body and sound overrides from the payload
  • updates the app-icon badge (badge, badge_increment)
  • registers action buttons from the payload's actions array
  • records the Delivered analytics event

Without an NSE, iOS still shows the notification, but you get no images, no badge increments and no delivery tracking.

Step 1: Add the NSE target​

  1. In Xcode: File → New → Target → Notification Service Extension. Name it, for example, NotificationService.
  2. When Xcode asks to activate the scheme, choose Cancel so you keep debugging the main app.
  3. Select the new target → General → set Minimum Deployments to the same version as your app (15.0 or higher).
Deployment target

Xcode sets a new extension to the latest iOS. On devices running an older iOS, the extension silently never runs — no crash and no log.

In the package's Add to Target list, choose your NSE target for AppsOnAir-AppPush-ServiceExt. Link it to the NSE only, never to the main app.

Module to import: AppsOnAir_AppPush_ServiceExt

Step 3: Share an App Group​

The App Group is how the NSE gets the App ID and subscription from the main app (for delivery receipts) and how it keeps the running badge count.

  1. Add the App Groups capability to the main app and the NSE target, with the same identifier:

    group.<your-main-app-bundle-id>.appsonair
  2. If you use exactly that name, the SDK finds it automatically. If you use any other name, add it to both Info.plist files:

    Info.plist (main app AND NSE)
    <key>AppsOnAirAppGroup</key>
    <string>group.com.yourcompany.app.appsonair</string>
  3. In the Apple Developer Portal → Identifiers, enable the App Group on both App IDs (main app and NSE), then regenerate the provisioning profiles.

Xcode writes the group to each target's .entitlements file automatically:

MyApp.entitlements / NotificationService.entitlements
<key>com.apple.security.application-groups</key>
<array>
<string>group.com.yourcompany.app.appsonair</string>
</array>
note

The automatic lookup inside the NSE removes the last part of the NSE bundle ID (com.acme.app.NotificationService → com.acme.app). Keep the NSE bundle ID as <main-app-bundle-id>.<Name> (the Xcode default), or set AppsOnAirAppGroup explicitly.

Step 4: Replace NotificationService​

NotificationService/NotificationService.swift
import AppsOnAir_AppPush_ServiceExt

class NotificationService: AppsOnAirNotificationServiceExtension {
// Nothing else required.
}

Optionally, change the content before the SDK applies its overrides and attachments:

import UserNotifications

class NotificationService: AppsOnAirNotificationServiceExtension {
override func modifyContent(_ content: UNMutableNotificationContent,
request: UNNotificationRequest) {
content.threadIdentifier = "orders"
}
}

Keep the Xcode-generated NSE Info.plist entries:

NotificationService/Info.plist
<key>NSExtension</key>
<dict>
<key>NSExtensionPointIdentifier</key>
<string>com.apple.usernotifications.service</string>
<key>NSExtensionPrincipalClass</key>
<string>$(PRODUCT_MODULE_NAME).NotificationService</string>
</dict>

Step 5: Send mutable-content​

iOS runs the NSE only when the APNs payload contains "mutable-content": 1. With the Send Push API, set "mutable_content": true.

APNs payload with image
{
"aps": {
"alert": { "title": "New offer", "body": "Tap to view" },
"mutable-content": 1
},
"notification_id": "notif-abc-123",
"big_picture": "https://cdn.example.com/offer.jpg"
}

Attachment rules

Source keysattachments (array of URLs or {id, url}, max 3) → otherwise big_picture → image_url → large_icon → video_url
ProtocolHTTPS only
Typesjpg, jpeg, png, gif, heic, webp, mp4, m4v, mov, mp3, m4a, wav, aiff
Limits15 s per download, 25 s in total. Apple's size limits apply (image 10 MB, audio 5 MB, video 50 MB)
FailureThe attachment is dropped and the notification is still shown

Notification Content Extension (Optional — Custom Long-Press View)​

The Notification Content Extension (NCE) replaces the expanded (long-press) view of a notification. The SDK's built-in AppsOnAirContentViewController shows:

  • a full-width image (200 pt high) from the first attachment, which the NSE downloads
  • the title (up to 2 lines)
  • the full body
What the NCE does not do
  • It shows images only. A video or audio attachment isn't played; the image area is hidden instead.
  • It doesn't download media itself. Set up the NSE as well if you want the image.
  • It doesn't need an App Group.

Step 1: Add the NCE target​

  1. File → New → Target → Notification Content Extension. Name it, for example, NotificationContent.
  2. Set Minimum Deployments to match your app (15.0 or higher).

Add AppsOnAir-AppPush-ContentExt to the NCE target only.

Module to import: AppsOnAir_AppPush_ContentExt

Step 3: Replace the view controller​

Delete MainInterface.storyboard (Move to Trash) — the SDK builds its UI in code. Then replace NotificationViewController.swift:

NotificationContent/NotificationViewController.swift
import UserNotifications
import AppsOnAir_AppPush_ContentExt

class NotificationViewController: AppsOnAirContentViewController {
// Optional: customise on top of the built-in image + title + body.
override func configure(with notification: UNNotification) {
super.configure(with: notification)
}
}
Fully custom UI

If you'd rather design the UI yourself, keep the storyboard, implement UNNotificationContentExtension in your own UIViewController, and don't link the SDK to the NCE at all. The NSE still downloads the attachment for you.

Step 4: Configure the NCE Info.plist​

Replace NSExtensionMainStoryboard with NSExtensionPrincipalClass, and set your category ID:

NotificationContent/Info.plist
<key>NSExtension</key>
<dict>
<key>NSExtensionAttributes</key>
<dict>
<!-- Must equal aps.category in the payload -->
<key>UNNotificationExtensionCategory</key>
<string>aoa_rich</string>
<key>UNNotificationExtensionInitialContentSizeRatio</key>
<real>1</real>
</dict>
<key>NSExtensionPointIdentifier</key>
<string>com.apple.usernotifications.content-extension</string>
<key>NSExtensionPrincipalClass</key>
<string>$(PRODUCT_MODULE_NAME).NotificationViewController</string>
</dict>

To handle several categories, make UNNotificationExtensionCategory an <array> of strings.

Step 5: Send the category​

iOS opens the NCE only when aps.category matches UNNotificationExtensionCategory. With the Send Push API, set "ios_category".

APNs payload for the NCE
{
"aps": {
"alert": { "title": "Order shipped", "body": "Long-press to see details" },
"category": "aoa_rich",
"mutable-content": 1
},
"notification_id": "notif-abc-123",
"big_picture": "https://cdn.example.com/parcel.jpg"
}
Action buttons and the NCE

If a payload has actions but no aps.category, the NSE assigns a generated category (aoa.actions.<ids>) so the buttons appear. That generated category won't match your NCE. Always send aps.category when you want the NCE.


Push Payload Reference​

Custom keys are siblings of aps, not inside it.

KeyTypeNotes
notification_idStringAvailable in callbacks as notification.id. Used for delivery receipts
title / subtitle / bodyStringOverride aps.alert. NSE only
soundString"default" or a bundled .caf/.aiff file name. Overrides aps.sound. NSE only
big_pictureString (https)Main image. NSE only. Wins over image_url and large_icon
image_urlString (https)Legacy alias for big_picture. NSE only
large_iconString (https)Used as the image only if the two keys above are absent. iOS has no separate thumbnail. NSE only
video_urlString (https)Used when no image key is set. NSE only
attachments[String] or [{id, url}]Up to 3 media URLs. Takes precedence over all keys above. NSE only
badgeIntAbsolute badge count. NSE only
badge_incrementIntDelta added to the running total. NSE and App Group
actions[{id, title, foreground?, destructive?}]Action buttons, registered by the NSE
aps.categoryStringRoutes the notification to your NCE
aps.content-availableInt1 with no alert makes the push silent: the app is woken in the background and nothing is shown

When Notifications Won't Be Delivered​

Push delivery depends on OS settings and device state — not just your code. The following conditions can silently block or delay delivery regardless of correct SDK integration.

ConditionAffectsEffect
Low Power ModeSilent onlyiOS suspends Background App Refresh and silent push delivery entirely while Low Power Mode is active. Delivery resumes when Low Power Mode is turned off or the device is charging. Visible notifications are unaffected.
Background App Refresh disabledSilent onlyIf the user has turned off Background App Refresh for the app (Settings → General → Background App Refresh → [Your App]), iOS will not wake the app for silent pushes.
Kill mode (app swiped off App Switcher)Silent onlyIf the user swipes the app off the App Switcher, iOS will not deliver silent pushes until the user manually relaunches the app. This is an iOS OS policy and cannot be worked around in code. Visible notifications are still delivered and tappable.
Apple rate limitingSilent onlyApple allows only a limited number of silent pushes per hour per device. If too many are sent in a short window, excess pushes are deferred or dropped silently.
Low batterySilent onlyAs battery level drops (roughly below 20%), iOS becomes more aggressive at deferring background work even without Low Power Mode enabled.
No network / poor signalSilent onlyAPNs holds the push until the device reconnects, up to the apns-expiration window in the request.
APNs on SimulatorSilent & visibleAPNs device tokens are not issued on the iOS Simulator. Always test push on a real device.
Permission deniedVisible onlySilent pushes don't require permission. Visible notifications are blocked if the user permanently denies permission.

Troubleshooting​

ProblemCauseFix
No APNs token on devicePush Notifications capability missingAdd via Signing & Capabilities
NSE not invokedmutable-content: 1 absent from payloadAdd it (mutable_content: true in the Send Push API)
NSE not invokedNSE deployment target is higher than the device's iOS versionSet the NSE's Minimum Deployments to your app's (15.0+)
Image not shownURL isn't HTTPS, file type isn't supported, or the download took longer than 15 sUse HTTPS and a supported type. Check the device console for [AppPushService NSE] logs
No Delivered analyticsApp Group missing or different between app and NSEUse the same group on both targets, and add AppsOnAirAppGroup to both Info.plist files if you don't use the default name
App Group not resolvable in NSE logsNSE can't find the groupAdd AppsOnAirAppGroup to the NSE Info.plist
CFPrefsPlistSource warningProvisioning profile doesn't include the App GroupEnable the group on both App IDs in the Developer Portal and regenerate the profiles
Badge increments ignoredNo App Group, so there's nowhere to store the running totalConfigure the App Group, or send an absolute badge
NCE not shown on long-pressaps.category missing or different from UNNotificationExtensionCategorySend the exact same category string
NCE shows a blank view / crashesNSExtensionMainStoryboard still set, or NSExtensionPrincipalClass has no module prefixUse $(PRODUCT_MODULE_NAME).NotificationViewController and delete the storyboard key
NCE shows text but no imageNSE not set up, or the attachment is a videoSet up the NSE. The built-in NCE renders images only
Archive fails: "Multiple commands produce AppsOnAir_AppPush.framework"Extension uses the deprecated AppsOnAir-AppPush/ServiceExtension or /ContentExtension subspecSwitch to the AppsOnAir-AppPush-ServiceExt / AppsOnAir-AppPush-ContentExt pods and update the import
pod install: "Unable to find a specification for AppsOnAir-AppPush-ServiceExt"Local spec index is out of dateRun pod install --repo-update
"Extension version must match parent app" warningBuild number differs between targetsUse the same CURRENT_PROJECT_VERSION on the app, NSE and NCE
Silent push handler never firesBackground Modes → Remote notifications missing, Low Power Mode on, or app swiped awayEnable the capability. See When Notifications Won't Be Delivered
Silent push handler never fires (custom AppDelegate)Your didReceiveRemoteNotification:fetchCompletionHandler: doesn't forward to the SDKCall AppPushService.handleSilentPush(_:fetchCompletionHandler:) from it
Background sync never firesregisterHandlers() called too lateCall it before any scene connects in application(_:didFinishLaunchingWithOptions:)
ObjC objc_subclassing_restrictedSubclassing a Swift base class from ObjCNSE: use AOAPushExtension. NCE: subclass AOAContentViewController

Setup Checklist​

Main app

  • AppsonairAppId is in Info.plist
  • Push Notifications and Background Modes → Remote notifications are enabled
  • AppsOnAir-AppPush is linked, and initialize() is called in didFinishLaunchingWithOptions
  • BGTaskSchedulerPermittedIdentifiers contains com.appsonair.push.background-sync

NSE (images, badge, delivery analytics)

  • NSE target created, with Minimum Deployments matching the app
  • AppsOnAir-AppPush-ServiceExt is linked to the NSE only
  • NotificationService subclasses AppsOnAirNotificationServiceExtension
  • The same App Group is on the app and the NSE, and enabled on both App IDs in the Developer Portal
  • AppsOnAirAppGroup is in both Info.plist files (unless you use group.<bundle-id>.appsonair)
  • Pushes are sent with mutable-content: 1

NCE (custom expanded view)

  • NCE target created, with Minimum Deployments matching the app
  • AppsOnAir-AppPush-ContentExt is linked to the NCE only
  • MainInterface.storyboard deleted, and NSExtensionPrincipalClass set
  • UNNotificationExtensionCategory equals the aps.category you send

Log Levels​

Set before initialize():

  • .none - Silent (default for production)
  • .error - Errors only
  • .warn - Warnings
  • .info - General info
  • .debug - Debug info
  • .verbose - All messages (use during development)