iOS
Install, initialize, and verify your first event on iOS.
iOS 13.0+ · Swift 5.9+ · Distribution: Swift Package Manager and CocoaPods · Latest: ios/1.5.4
Install (CocoaPods)
Add the pod to your Podfile:
target 'YourApp' do
pod 'SwanSDK', '~> 1.5'
endThen install:
pod installOpen the generated .xcworkspace (not the .xcodeproj) in Xcode going forward.
Swift Package Manager
The SDK is published on Swift Package Manager. In Xcode → File → Add Packages…, paste:
https://github.com/SwanCX/swan-ios-sdkPin to the latest version (currently 1.5.4) and add the SwanSDK product to your app target.
Or in Package.swift:
dependencies: [
.package(url: "https://github.com/SwanCX/swan-ios-sdk", from: "1.5.4"),
]Initialize
In your @main SwiftUI App:
import SwanSDK
@main
struct MyApp: App {
init() {
Swan.shared.initialize(
appId: "your-app-id",
config: SwanConfig(debug: false, production: true)
)
}
var body: some Scene { /* ... */ }
}UIKit equivalent:
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
Swan.shared.initialize(appId: "your-app-id")
return true
}
}Swan.shared.initialize(...) returns immediately. Device registration runs in the background; subscribe to addInitializedListener { } if you need to know when init resolves.
Push setup (Firebase Cloud Messaging)
Rich pushes (image / carousel) require a Notification Service Extension. Without it, iOS will show title + body only — images and carousel items will not render. See iOS — Rich pushes and extensions for the step-by-step extension setup. The token wire-up below is the minimum for plain pushes.
Swan delivers iOS pushes through Firebase Cloud Messaging, using the Firebase
credential configured for your app in Swan. Your app therefore registers its
Firebase registration token with Swan — not the raw APNs device token,
which Firebase rejects (the campaign's delivery report then shows
FCM_TOKEN_INVALID).
Add your iOS app to that Firebase project, upload your APNs authentication
key under Project settings → Cloud Messaging, add GoogleService-Info.plist
and the FirebaseMessaging package to your app, and enable the Push
Notifications capability. Then, in your AppDelegate:
import FirebaseCore
import FirebaseMessaging
import UserNotifications
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
FirebaseApp.configure()
// Initialize Swan first: a token passed before initialize(...) is ignored.
Swan.shared.initialize(appId: "your-app-id")
// A fresh install can receive the Firebase token before Swan has
// registered the device — register it again once initialization completes.
Swan.shared.addInitializedListener {
if let token = Messaging.messaging().fcmToken {
Swan.shared.registerAPNsTokenHex(token)
}
}
Messaging.messaging().delegate = self
UNUserNotificationCenter.current().delegate = self
application.registerForRemoteNotifications()
return true
}
}
extension AppDelegate: MessagingDelegate {
func messaging(_ messaging: Messaging,
didReceiveRegistrationToken fcmToken: String?) {
guard let fcmToken, !fcmToken.isEmpty else { return }
// Registers the Firebase token unchanged, despite the method name.
Swan.shared.registerAPNsTokenHex(fcmToken)
}
}
extension AppDelegate: UNUserNotificationCenterDelegate {
func userNotificationCenter(_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: @escaping () -> Void) {
Swan.shared.handleNotificationUserInfo(response.notification.request.content.userInfo)
completionHandler()
}
}Do not also call Swan.shared.registerAPNsToken(deviceToken) from
application(_:didRegisterForRemoteNotificationsWithDeviceToken:) — that
would replace the Firebase token with the APNs token. To confirm the setup,
check that Swan.shared.getPushToken() returns a Firebase token (it looks
like <instance-id>:APA91b…) and Swan.shared.isPushReady() returns true.
Only if you have set FirebaseAppDelegateProxyEnabled to NO in
Info.plist: Firebase no longer receives the APNs device token automatically,
so hand it to Firebase yourself — this is not a Swan registration, and
the token you register with Swan is still the Firebase token above:
// Only when FirebaseAppDelegateProxyEnabled = NO.
func application(_ application: UIApplication,
didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
Messaging.messaging().apnsToken = deviceToken // to Firebase, not to Swan
}See Push notifications → Provider setup for details.
Objective-C host apps
Mixed-language host apps drive the SDK through the SwanObjC facade —
a @objcMembers singleton that mirrors the customer-facing operations
on Swan through Obj-C-callable selectors.
#import <SwanSDK/SwanSDK-Swift.h>Initialize and identity
[[SwanObjC shared] initializeWithAppId:@"your-app-id"];
[[SwanObjC shared] addInitializedListener:^{
NSLog(@"SDK ready, swanIdentifier=%@", [SwanObjC shared].swanIdentifier);
}];
[[SwanObjC shared] identifyWithIdentifier:@"user-123"
attributes:@{ @"email": @"jane@example.com" }];
[[SwanObjC shared] enrichProfile:@{ @"plan": @"gold" }];
// Async login — completion fires on the main thread.
[[SwanObjC shared] loginWithCompletionWithIdentifier:@"user-123"
attributes:nil
completion:^(NSDictionary *result) {
NSLog(@"cdid=%@, profileSwitched=%@",
result[@"cdid"], result[@"profileSwitched"]);
}];
[[SwanObjC shared] logout];Event tracking and super-properties
[[SwanObjC shared] trackWithName:@"productViewed"
attributes:@{ @"productId": @"SKU-100" }];
[[SwanObjC shared] screenWithName:@"Home" attributes:nil];
[[SwanObjC shared] setCountry:@"AE"];
[[SwanObjC shared] setCurrency:@"AED"];
[[SwanObjC shared] setBusinessUnit:@"retail"];
[[SwanObjC shared] setCurrentScreenName:@"Home"];
[[SwanObjC shared] flush]; // force-drain the queue
NSInteger pending = [[SwanObjC shared] getQueueSize];Device info and location
NSDictionary *info = [[SwanObjC shared] getDeviceInfo];
NSLog(@"platform=%@ device=%@ cdid=%@",
info[@"platform"], info[@"deviceModal"], info[@"generatedCDID"]);
// Pass a negative number for accuracy to omit it.
[[SwanObjC shared] updateLocationWithLatitude:25.276987
longitude:55.296249
accuracy:10.0];
BOOL hasLocation = [[SwanObjC shared] isLocationEnabled];Push notifications
// In didFinishLaunchingWithOptions, after [FIRApp configure] and
// [[SwanObjC shared] initializeWithAppId:...]:
[[SwanObjC shared] addInitializedListener:^{
// A fresh install can receive the Firebase token before Swan has
// registered the device — register it again once initialization completes.
NSString *token = [FIRMessaging messaging].FCMToken;
if (token.length > 0) {
[[SwanObjC shared] registerAPNsTokenHex:token];
}
}];
[FIRMessaging messaging].delegate = self;
[application registerForRemoteNotifications];
// FIRMessagingDelegate — register the Firebase registration token
// (not the APNs device token):
- (void)messaging:(FIRMessaging *)messaging
didReceiveRegistrationToken:(NSString *)fcmToken {
if (fcmToken.length > 0) {
[[SwanObjC shared] registerAPNsTokenHex:fcmToken];
}
}
// Only if you set FirebaseAppDelegateProxyEnabled to NO in Info.plist —
// forward the APNs device token to Firebase (not to Swan):
- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
[FIRMessaging messaging].APNSToken = deviceToken;
}
// In didReceiveNotificationResponse: (user tapped a notification)
[[SwanObjC shared] handleNotificationUserInfo:response.notification.request.content.userInfo];
// In didReceiveRemoteNotification: (silent / data-only push)
[[SwanObjC shared] handlePushNotificationUserInfo:userInfo];
// Deep links from your scene delegate or URL handler:
BOOL handled = [[SwanObjC shared] handleDeepLink:url.absoluteString];
// Opt-out / re-enrol:
[[SwanObjC shared] unsubscribePush];
[[SwanObjC shared] subscribePush];Permissions (async → completion)
[[SwanObjC shared] requestNotificationPermissionWithCompletion:^(BOOL granted) {
NSLog(@"permission granted=%d", granted);
}];
[[SwanObjC shared] hasNotificationPermissionWithCompletion:^(BOOL granted) { /* … */ }];
[[SwanObjC shared] isPushEnabledWithCompletion:^(BOOL ready) { /* … */ }];Notification categories and badge
[[SwanObjC shared] createNotificationChannelWithId:@"swan_default"
name:@"General Notifications"
importance:4
soundName:@""]; // @"" = default sound
NSInteger badge = [[SwanObjC shared] getBadgeCount];
[[SwanObjC shared] setBadgeCount:0];
NSString *defaultId = [[SwanObjC shared] getNotificationChannelId];What stays Swift-only
The following surfaces remain Swift-only — write a small Swift bridging file in your host app to adapt them to NSObjects:
- Listeners that emit typed-struct payloads:
addNotificationOpenedListener,addDeepLinkOpenedListener,addPushNotificationReceivedListener,addSwanIdentifierChangedListener,addDeviceRegisteredListener,addPushTokenRegisteredListener, and the rest of the telemetry-event listeners. - The
SwanConfigvalue type (use theinitializeWithAppId:debug:production:overload from Obj-C instead). - The typed e-commerce helpers on
SwanEvents. Re-use the generictrackWithName:attributes:selector with the event name, as shown under E-commerce events. registrationStateStream(AsyncStream).
Verify the integration
Six [SwanSDK] * log markers emit at key lifecycle points:
| Marker | Means |
|---|---|
[SwanSDK] Starting SDK initialization... | initialize(...) called |
[SwanSDK] SDK initialization completed successfully | init resolved |
[SwanSDK] Device registered successfully: <uuid> | device-register HTTP call succeeded; CDID granted |
[SwanSDK] Foreground notification received: <messageId> | push arrived while app foreground |
[SwanSDK] Notification displayed successfully with ID: <messageId> | notification posted to OS |
[SwanSDK] Notification ACK queued | click ACK queued for backend |
Visible in the Xcode debug console or via log show on a real device.
Track your first event
SwanEvents.productViewed(attributes: ["productId": "SKU-100"])Next steps
Identify users
Sign-in flow, anonymous-to-identified merge, profile enrichment, logout.
E-commerce events
What to call for each shopper action, and what to pass.
Push notifications
Token wire-up details, categories, cold-start deep linking, iOS payload reference.
iOS — Rich pushes and extensions
Add a Notification Service Extension to render image and carousel pushes. Required for any non-text push on iOS.