# Push notifications

Start a Screeb survey when the user receives or taps a push notification, by sending the survey id in the notification payload.

Screeb does not send push notifications. Your push service (Firebase Cloud Messaging, for example) sends them, with a survey id in the payload, and your app starts that survey when the notification arrives or when the user taps it.

You need a survey in the Screeb admin and a push service already working in your app.

## Add the survey id to the payload

In your push service, create the notification (title, body, audience, schedule) and add a custom data entry with the key `screeb` and the survey id as value. In the Firebase console, custom data is in the "Additional options" step.

```json
{
  "screeb": "<SURVEY-ID>"
}
```

The key `screeb` is a convention used in the examples below: any key works, as long as your app reads the same one.

## App in the foreground

When the app is in the foreground, iOS calls `userNotificationCenter(_:willPresent:withCompletionHandler:)` on the notification center delegate. Start the survey there.

```swift
import Screeb
import UIKit
import UserNotifications

extension AppDelegate: UNUserNotificationCenterDelegate {
    func userNotificationCenter(
        _ center: UNUserNotificationCenter,
        willPresent notification: UNNotification,
        withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void
    ) {
        startScreebSurvey(from: notification)
        completionHandler([.banner, .sound])
    }

    func startScreebSurvey(from notification: UNNotification) {
        let userInfo = notification.request.content.userInfo
        if let surveyId = userInfo["screeb"] as? String {
            Screeb.startSurvey(surveyId: surveyId)
        }
    }
}
```

Set the delegate in `application(_:didFinishLaunchingWithOptions:)`, or iOS never calls it:

```swift
UNUserNotificationCenter.current().delegate = self
```

## App in the background

When the app is in the background, the system shows the notification. Tapping it opens the app with the payload.

```swift
extension AppDelegate {
    func userNotificationCenter(
        _ center: UNUserNotificationCenter,
        didReceive response: UNNotificationResponse,
        withCompletionHandler completionHandler: @escaping () -> Void
    ) {
        startScreebSurvey(from: response.notification)
        completionHandler()
    }
}
```

To add hidden fields, force the language or start a message the same way, see [Start a survey programmatically](https://developers.screeb.app/sdk-ios/start-survey-programmatically) and [Start a message programmatically](https://developers.screeb.app/sdk-ios/start-message-programmatically).
