# iOS Developer Guide

Beta Feature
Mobile Push is currently in beta. Features, APIs, and implementation details may change before general availability.

## Overview

This guide provides implementation requirements for integrating Engage Studio Mobile Push notifications in your iOS app using the Treasure Data iOS SDK. Your development team must implement the following functionality:

1. **APNs/FCM Integration**: Receive push notifications via Apple Push Notification Service and Firebase Cloud Messaging
2. **Token Management**: Register and update device tokens with Treasure Data
3. **Rich Notifications**: Display notifications with images using Notification Service Extension
4. **Event Tracking**: Track user interactions (delivery, open, dismiss, links) using Treasure Data SDK
5. **Automated Data Upload**: Treasure Data SDK automatically handles event upload to Treasure Data


Sample Implementation Available
A complete, production-ready sample application is available on GitHub:

**[Treasure Data Mobile Push - iOS Sample](https://github.com/treasure-data/engage-push-notification-sample/tree/main/ios)**

The sample includes:

- Complete AppDelegate implementation with FCM and Treasure Data SDK integration
- Notification Service Extension for rich media
- Event tracking with Treasure Data SDK
- Deep link and web link handling


Clone the repository and use it as a reference for your implementation.

## Native SDK Preview: Device Token Registration

The preview Mobile SDK includes `registerDeviceToken` for sending an APNs or FCM device token to Treasure AI. Your app still obtains the token, requests notification permission, receives and displays notifications, and handles notification taps. See [Device Token Registration](/products/marketing-cloud/engage-studio/channels/mobile-push/device-token-registration) for the SDK API and the preview record schema.

Push and Hosted Pages
When a Push payload contains a URL, the app can pass it to the SDK to display a Hosted Pages experience. The SDK does not currently own the APNs or FCM receiver.

## Requirements

| Component | Requirement |
|  --- | --- |
| **Minimum iOS Version** | iOS 15.0 or later |
| **Language** | Swift (recommended) or Objective-C |
| **Required Frameworks** | - Firebase Messaging SDK 12.7.0+
- Treasure Data iOS SDK 1.2.1+
- UserNotifications framework
- SafariServices (for web link handling)

 |
| **Xcode Version** | Xcode 16.2 or later |
| **Tracked Events** | `delivery`, `open`, `dismiss`, `deeplink_open`, `link_open`, `token_register` |


## Architecture Overview

Your iOS app implementation consists of the following components:

### 1. AppDelegate Configuration

**Purpose:** Initialize Firebase, Treasure Data SDK, and configure notification delegates

**Key Responsibilities:**

- Initialize Firebase SDK
- Initialize Treasure Data SDK with endpoint and database configuration
- Set notification center delegates
- Request notification permissions from user
- Register for remote notifications
- Handle notification events in foreground and background


**Reference:** See `AppDelegate.swift` in the [sample repository](https://github.com/treasure-data/engage-push-notification-sample/tree/main/ios)

### 2. Notification Service Extension

**Purpose:** Download and attach images to notifications

**Key Responsibilities:**

- Receive notification before display
- Extract `image` from the payload
- Download image from remote URL
- Create UNNotificationAttachment
- Add attachment to notification content


**Reference:** See `NotificationService.swift` in the [sample repository](https://github.com/treasure-data/engage-push-notification-sample/tree/main/ios)

### 3. Event Tracking

**Purpose:** Manage event tracking with Treasure Data SDK

**Key Responsibilities:**

- Track all push notification events using Treasure Data SDK
- Record `delivery`, `open`, and `dismiss` in `AppDelegate`, and link events in `TrackingService`
- Associate events with FCM token and user ID
- Manage event data formatting


**Reference:** See `AppDelegate.swift` and `TrackingService.swift` in the [sample repository](https://github.com/treasure-data/engage-push-notification-sample/tree/main/ios)

### 4. Deep Link Handler

**Purpose:** Handle deep links from notifications

**Key Responsibilities:**

- Receive deep link URLs via SceneDelegate or AppDelegate
- Parse URL scheme and path
- Navigate to appropriate screen based on deep link
- Open web URLs in Safari
- Track deep link events


**Reference:** See `SceneDelegate.swift` in the [sample repository](https://github.com/treasure-data/engage-push-notification-sample/tree/main/ios)

## Project Setup

### Step 1: Generate Xcode Project with XcodeGen

The sample app uses XcodeGen to generate the Xcode project. Install XcodeGen:

```bash
brew install xcodegen
```

Generate the Xcode project:

```bash
cd ios
xcodegen generate
```

### Step 2: Add Firebase and Treasure Data SDK

The project uses Swift Package Manager for dependency management. Dependencies are defined in `project.yml`:

**Firebase iOS SDK** (12.7.0+):

- `FirebaseMessaging`
- `FirebaseAnalytics`


**Treasure Data iOS SDK** (1.2.1+):

- Complete SDK for event tracking and data upload


Dependencies are automatically resolved when you open the generated Xcode project.

### Step 3: Configure Firebase

1. Download `GoogleService-Info.plist` from Firebase Console
2. Copy the file to your project:

```bash
cp GoogleService-Info.plist ios/TDPushSample/GoogleService-Info.plist
```
3. Ensure the file is added to your main app target in Xcode


### Step 4: Configure Treasure Data in Info.plist

Add your Treasure Data configuration to `Info.plist`:

```xml
<key>TDWriteKey</key>
<string>your_write_api_key_here</string>
<key>TDDatabase</key>
<string>mobile</string>
<key>TDTable</key>
<string>push_events</string>
<key>TDEndpoint</key>
<string>https://in.treasuredata.com</string>
```

**Important:** Do not commit your actual API key to version control. Use placeholder values and document the required configuration.

### Step 5: Configure Capabilities in Xcode

1. Select your project in Project Navigator
2. Select your app target
3. Go to **Signing & Capabilities** tab
4. Click **+ Capability** and add:
  - **Push Notifications**
  - **Background Modes** → Check **Remote notifications**


### Step 6: Create Notification Service Extension (for Rich Media)

To support images in notifications, you need a Notification Service Extension:

1. In Xcode, go to **File** > **New** > **Target**
2. Select **Notification Service Extension**
3. Enter extension name (e.g., `NotificationService`)
4. Click **Finish**


### Step 7: Configure Info.plist for Deep Links

1. Register the URL scheme in `Info.plist`:


```xml
<key>CFBundleURLTypes</key>
<array>
    <dict>
        <key>CFBundleURLSchemes</key>
        <array>
            <string>myapp</string>
        </array>
        <key>CFBundleURLName</key>
        <string>com.example.myapp</string>
    </dict>
</array>
```

1. Configure the scheme and permitted destinations for the sample's notification tap handler:


```xml
<key>TDDeepLinkScheme</key>
<string>myapp</string>
<key>TDAllowedDeepLinkHosts</key>
<array>
    <string>product</string>
</array>
<key>TDAllowedDomains</key>
<array>
    <string>example.com</string>
</array>
```

**Configuration Notes:**

- This example allows `myapp://product/12345` and `https://example.com/promo`.
- `TDDeepLinkScheme` must match the scheme registered in `CFBundleURLSchemes`.
- The sample configures these keys for `tdpushsample`. Retain those values when testing the unmodified sample fixtures.


## Data Payload Schema

Your app receives the following JSON structure in the notification `userInfo`. APNs `aps` and the FCM custom data fields are placed at the root of `userInfo`.

```json
{
  "aps": {
    "alert": {
      "title": "Special Offer!",
      "body": "Get 20% off your next purchase"
    },
    "content-available": 1,
    "category": "default",
    "mutable-content": 1
  },
  "tdCampaignId": "cmp_20251214_promo",
  "title": "Special Offer!",
  "message": "Get 20% off your next purchase",
  "image": "https://cdn.example.com/banner.png",
  "link": "myapp://product/12345"
}
```

| Field | Type | Required | Description |
|  --- | --- | --- | --- |
| `aps.content-available` | Integer | Yes | Set to `1` by Engage Studio. Requests background execution so your app can record a `delivery` event when iOS invokes the callback. Background execution is not guaranteed. |
| `aps.category` | String | Yes | Set to `default` by Engage Studio. Identifies the notification category your app registers so it can receive a callback when the user dismisses the notification, enabling `dismiss` tracking. |
| `aps.mutable-content` | Integer | No | Set to `1` for image notifications. Enables the Notification Service Extension to attach the image. |
| `tdCampaignId` | String | Yes | Unique campaign identifier from Engage Studio |
| `title` | String | Yes | Notification title |
| `message` | String | Yes | Notification body text. The displayed iOS notification body is in `aps.alert.body`. |
| `image` | String | No | URL for the notification image. Also set in the FCM APNs image option for image notifications. |
| `link` | String | No | Web URL or deep link selected by **On click behavior**. Omitted for **Open app**, which opens the app without additional URL navigation. |


### APNs fields for delivery and dismiss tracking

Engage Studio automatically adds two fields to the `aps` dictionary of every iOS push notification so that your app can track delivery and dismiss events:

How these fields work
- **`content-available: 1`** — Requests a brief background update so your app can record a **delivery** event. iOS controls whether and when to run background work, so this callback is not guaranteed. See Apple's [Pushing background updates to your app](https://developer.apple.com/documentation/usernotifications/pushing-background-updates-to-your-app).
- **`category: default`** — Associates the notification with a notification category. When your app registers a matching category that allows a custom dismiss action, iOS calls your delegate when the user swipes the notification away, enabling **dismiss** tracking. See Apple's [Generating a remote notification](https://developer.apple.com/documentation/usernotifications/generating-a-remote-notification).


These payload fields are sent by Engage Studio automatically — no campaign configuration is required. However, to actually capture delivery and dismiss events your app must complete the [required app-side setup](#enabling-delivery-and-dismiss-tracking-required-app-side-setup) described below.

## Event Tracking

Your app must track the following events and send them to Treasure Data:

| Event Type | When to Track | Required Fields |
|  --- | --- | --- |
| `delivery` | When iOS invokes the foreground notification delegate or the background remote-notification callback. Background execution is best-effort. | `campaign_id`, `platform`, `time` |
| `open` | When user taps the notification | `campaign_id`, `platform`, `time` |
| `dismiss` | When user dismisses the notification | `campaign_id`, `platform`, `time` |
| `link_open` | When user taps a web link | `campaign_id`, `platform`, `time`, `value` (URL) |
| `deeplink_open` | When user taps a deep link | `campaign_id`, `platform`, `time`, `value` (URI) |
| `token_register` | When FCM token is obtained or refreshed | `fcm_token`, `platform`, `time`, `user_id` (if logged in) |


**Implementation Notes:**

- **User ID:** `user_id` is not a required field in the shared event schema. Include it in `token_register` when the user is logged in; anonymous users can omit it or send `null`. Treasure AI can associate earlier events with the user through the registered `fcm_token`.
- **Campaign ID:** Record `userInfo["tdCampaignId"]` in the event's `campaign_id` field.
- **FCM message ID:** Record `userInfo["gcm.message_id"]` in `message_id`. FCM supplies this metadata separately from the custom data fields.
- **Upload:** Record events with the Treasure Data SDK and call `uploadEvents()` to send them. The SDK handles event queuing and upload retries.


Delivery and dismiss events require app-side setup
The background `delivery` event and the `dismiss` event rely on the `content-available` and `category` fields that Engage Studio adds to the payload. iOS may defer or omit background execution. To capture these events when iOS invokes the relevant callbacks, complete the [Enabling Delivery and Dismiss Tracking](#enabling-delivery-and-dismiss-tracking-required-app-side-setup) setup below.

See the [Push Events Table](/products/marketing-cloud/engage-studio/channels/mobile-push/push-events-table) documentation for complete schema details.

## Enabling Delivery and Dismiss Tracking (Required App-Side Setup)

Engage Studio adds `content-available: 1` and `category: default` to the iOS push payload automatically. These fields allow your app to record `delivery` and `dismiss` events when iOS invokes the relevant callbacks; they do not guarantee background execution.

### 1. Enable Background Modes

Enable **Background Modes → Remote notifications** for your app target, as described in [Step 5: Configure Capabilities in Xcode](#step-5-configure-capabilities-in-xcode). This lets iOS run your app briefly for a notification with `content-available: 1` when system conditions allow, so your app can record a `delivery` event.

### 2. Register the `default` notification category

Register a `UNNotificationCategory` with the identifier `default` and the `.customDismissAction` option so iOS notifies your app when a notification is dismissed. Set the category when you configure the notification center (for example, in `application(_:didFinishLaunchingWithOptions:)`):

```swift
let defaultCategory = UNNotificationCategory(
    identifier: "default",
    actions: [],
    intentIdentifiers: [],
    options: [.customDismissAction]
)
UNUserNotificationCenter.current().setNotificationCategories([defaultCategory])
```

The `identifier` must match the `category` value (`default`) sent in the payload. `setNotificationCategories` replaces all registered categories, so include any categories used by other SDKs or app features in the same set.

### 3. Track the dismiss event

iOS calls `userNotificationCenter(_:didReceive:withCompletionHandler:)` with `UNNotificationDismissActionIdentifier` as the action identifier when the user swipes the notification away. Use `handleNotificationResponse` to identify the action and record the `dismiss` event:

```swift
func userNotificationCenter(
    _ center: UNUserNotificationCenter,
    didReceive response: UNNotificationResponse,
    withCompletionHandler completionHandler: @escaping () -> Void
) {
    DispatchQueue.main.async {
        self.handleNotificationResponse(response)
        completionHandler()
    }
}
```

### 4. Track background delivery

When iOS invokes `application(_:didReceiveRemoteNotification:fetchCompletionHandler:)` for a notification with `content-available: 1`, record the `delivery` event there. Guard the call with `applicationState != .active` to avoid duplicating foreground events already tracked in the `willPresent` delegate. Background execution is best-effort:

```swift
func application(
    _ application: UIApplication,
    didReceiveRemoteNotification userInfo: [AnyHashable: Any],
    fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void
) {
    // Only track background deliveries here; foreground deliveries are
    // tracked in the willPresent delegate to avoid duplicate events.
    if application.applicationState != .active {
        trackDeliveryEvent(userInfo: userInfo)
    }
    completionHandler(.newData)
}
```

Reference Implementation
The [sample repository](https://github.com/treasure-data/engage-push-notification-sample/tree/main/ios) handles notification responses as follows:

- `AppDelegate.handleNotificationResponse` records `open` or `dismiss` according to the action identifier.
- `SceneDelegate` also passes `connectionOptions.notificationResponse` to the same helper, which deduplicates responses by request identifier and action identifier.
- Navigation after a tap waits until the Scene becomes active.


## Testing

### Test on Physical Device

#### Send an Engage Studio test

1. Run your app on a physical iOS device and obtain its current FCM token from the app logs.
2. In Engage Studio, open a Mobile Push campaign and select the **Campaign Content** tab.
3. Click **Create mobile push notification**, or **Edit** for existing content. The **Mobile Push Notification Editor** opens.
4. Under **Mobile push authentication**, select the authentication configured for the app's Firebase project.
5. Enter **Title** and **Message**. To test images or tap behavior, configure **Image** and **On click behavior**.
6. Click **Send test**.
7. Enter the token in **Test device token**.
8. Click **Send**.
9. Verify the notification, tap behavior, and campaign events.


Repeat the test in the foreground and background, and test tapping a notification when the app is terminated. Confirm that each tap records one `open` event and opens the configured screen or web link. **Open app** displays the app's screen.

**Note:** Background delivery tracking depends on iOS invoking the background callback. Background execution is not guaranteed, so do not require a `delivery` event for the terminated-state tap check.

### Test local notification handling on Simulator

Run the app on an iOS 15+ Simulator and allow notifications.

1. Save the sample's [test-notification.apns](https://github.com/treasure-data/engage-push-notification-sample/blob/main/shared/test-payloads/test-notification.apns) locally.
2. Set `Simulator Target Bundle` to your app's bundle ID. Set `link` to a deep link supported by your app, such as `myapp://product/12345`.
3. Send the payload to the Simulator:


```bash
xcrun simctl push booted com.example.myapp test-notification.apns
```

1. Verify notification display and tap behavior.


Local test scope
- `simctl push` bypasses FCM and APNs delivery and does not include an FCM-generated message ID.
- Use a physical device with Engage Studio **Send test** to verify rich images, campaign delivery, and the associated event tracking.


### Verify Event Tracking

Query Treasure Data to confirm events are being logged:

```sql
SELECT
  time,
  type,
  campaign_id,
  platform
FROM mobile.push_events
WHERE platform = 'ios'
ORDER BY time DESC
LIMIT 100
```

## User ID Association

To link push notification events with specific users, pass the `user_id` when registering the FCM token.

**Implementation Notes:**

- **Logged-in users**: Include `user_id` (e.g., customer ID, email hash) in token registration events
- **Not logged-in users**: Pass `nil` for `user_id` — Treasure Data will associate the token later when the user logs in
- **Name resolution**: Treasure Data links events by matching `fcm_token` values over time


## Troubleshooting

### Notifications not received

1. **Check APNs certificate**: Verify APNs authentication key is uploaded to Firebase Console
2. **Check Bundle ID**: Ensure Bundle ID in Xcode matches Firebase registration (case-sensitive)
3. **Check notification permissions**: Verify app has notification permission in Settings > Notifications
4. **Check device registration**: Confirm `didRegisterForRemoteNotificationsWithDeviceToken` is called
5. **Check campaign delivery**: Use Engage Studio **Send test** with the **Mobile push authentication** configured for the Firebase project and the current FCM token.


### Rich images not displaying

1. **Verify Notification Service Extension**: Check extension is properly configured and added to app
2. **Check image URL**: Ensure URL is HTTPS and image is accessible
3. **Check extension logs**: Use Console.app to view extension logs
4. **Check file size**: Large images may timeout (limit ~10MB)


### Events not appearing in Treasure Data

1. **Check write key**: Verify `TDWriteKey` in Info.plist is correct and active
2. **Check endpoint**: Ensure `TDEndpoint` matches your region (US, Tokyo, EU)
3. **Check table name**: Confirm `TDDatabase` and `TDTable` exist in Treasure Data
4. **Check SDK initialization**: Verify Treasure Data SDK is initialized in AppDelegate
5. **Enable logging**: Add `TreasureData.enableLogging()` to see SDK activity
6. **Force upload**: Try calling `TreasureData.sharedInstance().uploadEvents()` manually


### Deep links not working

1. **Verify URL scheme**: Check `Info.plist` has correct `CFBundleURLTypes` configuration
2. **Test deep link**: Use Safari to test: Enter `myapp://test` in address bar
3. **Check scene delegate**: Ensure `scene(_:openURLContexts:)` is implemented
4. **Check URI format**: Verify deep link starts with your registered scheme


## Security Best Practices

1. **Protect API Keys**:
  - Never commit actual `TDWriteKey` to source control
  - Use placeholder values in Info.plist committed to Git
  - Document required configuration separately
  - Use write-only keys (not master keys)
  - Consider using Keychain for production apps
2. **Validate Deep Links**:
  - Always validate deep link destinations before navigating
  - Implement URL allowlists for sensitive actions
  - Sanitize deep link parameters
3. **Secure Event Data**:
  - Do not include PII (personally identifiable information) in event payloads
  - Use hashed or anonymized user IDs when possible
4. **Network Security**:
  - Always use HTTPS for API endpoints
  - Implement App Transport Security (ATS)
  - Consider certificate pinning for production apps


## Sample Repository

Complete, production-ready implementation:

**[https://github.com/treasure-data/engage-push-notification-sample/tree/main/ios](https://github.com/treasure-data/engage-push-notification-sample/tree/main/ios)**

The repository includes:

- Full source code with inline documentation
- XcodeGen project configuration
- Swift Package Manager dependency management
- Treasure Data SDK integration examples
- Testing instructions
- Security best practices


## Implementation Guide

This section provides detailed instructions for building and testing the sample application.

### Project Structure

The sample repository follows this directory structure:

```
ios/
├── TDPushSample/
│   ├── AppDelegate.swift           # Firebase & TD SDK init, notification delegates
│   ├── SceneDelegate.swift         # Deep link routing
│   ├── ViewController.swift        # Main UI
│   ├── TrackingService.swift       # Event tracking with TD SDK
│   ├── CategoryView.swift          # Category example
│   ├── ProductDetailView.swift     # Product detail example
│   ├── Models/                     # Data models
│   ├── Utils/                      # Utility classes
│   ├── Assets.xcassets
│   ├── Info.plist                  # App config & TD settings
│   └── GoogleService-Info.plist.example  # Firebase config template
├── NotificationService/             # Extension for rich media
│   └── NotificationService.swift
├── project.yml                      # XcodeGen configuration
└── TDPushSample.xcodeproj/         # Generated by XcodeGen
```

### Build and Run Instructions

#### Prerequisites

- macOS 14.5 or later
- Xcode 16.2 or later
- XcodeGen installed via Homebrew


#### Setup Steps

1. Clone the repository:


```bash
git clone https://github.com/treasure-data/engage-push-notification-sample.git
cd engage-push-notification-sample/ios
```

1. Install XcodeGen (if not already installed):


```bash
brew install xcodegen
```

1. Generate Xcode project:


```bash
xcodegen generate
```

1. Configure Firebase:
  - Download `GoogleService-Info.plist` from your Firebase project
  - Copy it to `TDPushSample/GoogleService-Info.plist`
2. Configure Treasure Data:
  - Open `TDPushSample/Info.plist`
  - Update the following keys with your configuration:
    - `TDWriteKey`: Your write-only API key
    - `TDDatabase`: Your database name (e.g., "mobile")
    - `TDTable`: Your table name (e.g., "push_events")
    - `TDEndpoint`: Your TD endpoint (e.g., "https://in.treasuredata.com")
3. Open project in Xcode:


```bash
open TDPushSample.xcodeproj
```

1. Build and run:
  - Select target device/simulator
  - Press Cmd+R to build and run
  - Swift Package Manager will automatically resolve dependencies


### Testing Workflow

#### Prerequisites

Before testing, ensure you have:

- [ ] Firebase project with iOS app registered
- [ ] APNs authentication key uploaded to Firebase Console
- [ ] `GoogleService-Info.plist` downloaded and added to project
- [ ] Treasure Data database and table created
- [ ] Write-only API key obtained
- [ ] Physical iOS device or iOS 15+ simulator


#### Test local notification handling on Simulator

1. Open the generated `TDPushSample.xcodeproj`, select an available simulator, and press Cmd+R to install and launch the app. Allow notifications when prompted.
2. From the sample repository's `ios` directory, inject the simulator fixture:


```bash
xcrun simctl push booted com.treasuredata.pushsample ../shared/test-payloads/test-notification.apns
```

1. Verify notification display and navigation to the product screen for `tdpushsample://product/12345`.


See [Test local notification handling on Simulator](#test-local-notification-handling-on-simulator) for the scope of this test.

#### Test on Physical Device

1. Connect device via USB
2. Enable Developer Mode on device:
  - Settings > Privacy & Security > Developer Mode
3. Build and install app from Xcode
4. Check Xcode console for FCM token:


```
FCM token: [your-token-here]
```

1. Send a campaign test from Engage Studio:
Follow [Send an Engage Studio test](#send-an-engage-studio-test) using the device's current FCM token.
2. Verify that the notification appears and that tap behavior and campaign events match the configured content.


#### Verify Event Tracking

Query Treasure Data to confirm events are being logged:

```sql
SELECT
  time,
  type,
  campaign_id,
  platform,
  user_id
FROM mobile.push_events
WHERE platform = 'ios'
  AND time > td_time_add(now(), '-1h', 'JST')
ORDER BY time DESC
LIMIT 20
```

Expected event sequence:

1. `token_register` - When app launches
2. `delivery` - When iOS invokes the foreground or background delivery callback; background execution is best-effort
3. `open` - When user taps notification
4. `link_open` or `deeplink_open` - If notification contains links


### Implementation Checklist

Use this checklist when implementing push notifications in your own app:

#### Phase 1: Project Setup

- [ ] Install XcodeGen: `brew install xcodegen`
- [ ] Create or clone iOS project
- [ ] Generate Xcode project with `xcodegen generate`
- [ ] Add Push Notifications capability in Xcode
- [ ] Add Background Modes capability (Remote notifications)
- [ ] Configure URL scheme for deep links in Info.plist
- [ ] Download and add `GoogleService-Info.plist`
- [ ] Configure Treasure Data settings in Info.plist


#### Phase 2: Core Components

- [ ] Implement Firebase initialization in `AppDelegate`
- [ ] Implement Treasure Data SDK initialization in `AppDelegate`
- [ ] Configure `UNUserNotificationCenter` delegate
- [ ] Configure Firebase Messaging delegate
- [ ] Request notification permissions
- [ ] Register for remote notifications
- [ ] Create `TrackingService` for event tracking with TD SDK


#### Phase 3: Notification Service Extension

- [ ] Create Notification Service Extension target
- [ ] Implement `NotificationService` class
- [ ] Add image download logic
- [ ] Create `UNNotificationAttachment` for images
- [ ] Handle extension timeout gracefully


#### Phase 4: Event Tracking

- [ ] Track `delivery` events in `willPresent` delegate using TD SDK
- [ ] Register the `default` notification category with `.customDismissAction`
- [ ] Confirm Background Modes (Remote notifications) is enabled for background delivery
- [ ] Track background `delivery` events in `didReceiveRemoteNotification` using TD SDK
- [ ] Track `open` events in `didReceive response` delegate using TD SDK
- [ ] Track `dismiss` events for `UNNotificationDismissActionIdentifier` in `didReceive response` using TD SDK
- [ ] Track `link_open` events for web links using TD SDK
- [ ] Track `deeplink_open` events for app links using TD SDK
- [ ] Track `token_register` events on app launch and token refresh using TD SDK


#### Phase 5: Deep Link Handling

- [ ] Implement `scene(_:openURLContexts:)` in SceneDelegate
- [ ] Parse deep link URL scheme and path
- [ ] Navigate to appropriate screen based on deep link
- [ ] Handle web links with Safari or SFSafariViewController
- [ ] Validate deep link destinations
- [ ] Configure `TDDeepLinkScheme`, `TDAllowedDeepLinkHosts`, and `TDAllowedDomains` for the sample's tap handler


#### Phase 6: Configuration and Security

- [ ] Configure `TDWriteKey`, `TDDatabase`, `TDTable`, `TDEndpoint` in Info.plist
- [ ] Use placeholder values for API keys in version control
- [ ] Document required configuration separately
- [ ] Implement error handling for TD SDK operations
- [ ] Add logging for debugging using `TreasureData.enableLogging()`


#### Phase 7: Testing

- [ ] Test local notification handling on simulator with the `.apns` fixture
- [ ] Test campaign delivery and events on a physical device with Engage Studio **Send test**
- [ ] Test rich media (images) in notifications
- [ ] Test deep link navigation
- [ ] Test web link opening
- [ ] Verify events appear in Treasure Data
- [ ] Test with background app state
- [ ] Test with force-quit app state


### Build Troubleshooting

#### "No such module 'Firebase'" or "No such module 'TreasureData'" Error

- Ensure Swift Package Manager resolved dependencies
- Try: File > Packages > Reset Package Caches
- Clean build folder: Product > Clean Build Folder (Cmd+Shift+K)
- Regenerate project: `xcodegen generate`


#### Notification Service Extension Not Loading Images

- Check image URL is HTTPS
- Verify image is accessible (test URL in browser)
- Check extension logs in Console.app
- Ensure extension target has increased memory limit in scheme settings


#### Events Not Appearing in Treasure Data

- Verify `TDWriteKey` in Info.plist is correct
- Check `TDEndpoint` matches your region
- Confirm `TDDatabase` and `TDTable` names are correct
- Verify TD SDK is initialized in AppDelegate
- Enable logging: `TreasureData.enableLogging()`
- Force upload: `TreasureData.sharedInstance().uploadEvents()`


#### Deep Links Not Opening

- Verify URL scheme in Info.plist matches deep link
- Test deep link from Safari: enter `myapp://test` in address bar
- Check `scene(_:openURLContexts:)` is implemented in SceneDelegate
- For iOS 12 and below, implement in AppDelegate instead


## Next Steps

1. **Clone the sample repository** and review the implementation
2. **Configure Firebase** following the [Mobile Push Setup](/products/marketing-cloud/engage-studio/channels/mobile-push/mobile-push-setup) guide
3. **Implement the components** in your iOS app
4. **Test notification delivery** and event tracking
5. **Review event data** in the [Push Events Table](/products/marketing-cloud/engage-studio/channels/mobile-push/push-events-table)
6. **Create your first campaign** in [Engage Studio](/products/marketing-cloud/engage-studio/channels/mobile-push)


## Related Documentation

- [Mobile Push Setup](/products/marketing-cloud/engage-studio/channels/mobile-push/mobile-push-setup) - Firebase and APNs configuration
- [Android Developer Guide](/products/marketing-cloud/engage-studio/channels/mobile-push/developer-guide-android) - Android implementation guide
- [Push Events Table](/products/marketing-cloud/engage-studio/channels/mobile-push/push-events-table) - Event schema and analytics queries
- [Campaign Creation](/products/marketing-cloud/engage-studio/channels/mobile-push) - Create Mobile Push campaigns