> ## Documentation Index
> Fetch the complete documentation index at: https://documentation.qonversion.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Configuring Notifications

## iOS Push Notifications

### Getting started

To set up push notifications, you need to complete the following steps:

* Make sure you have completed all of the required steps in [this guide](creating-push-notifications)
* Turn on push notifications in your project's settings
* Set the push notifications on the client side.

### Enabling the Push Notification Service

* Select your app target
* Click the **Signing & Capabilities** tab
* Click the **+ Capability** button.
* Type “push notifications” in the filter field
* Press Enter

<img src="https://mintcdn.com/qonversion/VTmQeWlObtMNi7PY/images/docs/7f44e09-Capability.png?fit=max&auto=format&n=VTmQeWlObtMNi7PY&q=85&s=11966fa761edbaf202f1f73249c7a26a" alt="3060" width="3060" height="2083" data-path="images/docs/7f44e09-Capability.png" />

After adding the push notifications entitlement, your project should look like this:

<img src="https://mintcdn.com/qonversion/VTmQeWlObtMNi7PY/images/docs/7f412dc-Project.png?fit=max&auto=format&n=VTmQeWlObtMNi7PY&q=85&s=cd708502da9c06076ded843c059061c5" alt="3062" width="3062" height="2086" data-path="images/docs/7f412dc-Project.png" />

### Asking for User Notifications Permission

There are two steps to register for push notifications:

* Get the user’s permission to show notifications
* Register the device to receive remote notifications

Open your **AppDelegate** and add the following import:

```swift theme={null}
import UserNotifications
```

```objectivec theme={null}
#import <UserNotifications/UserNotifications.h>
```

Then, add the following method:

```swift theme={null}
func registerForNotifications() {
    // Set delegate to handle push notification further
    UNUserNotificationCenter.current().delegate = self
  
    // Get the user’s permission to show notifications 
    UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { granted, _ in
        guard granted else { return }
        
        UNUserNotificationCenter.current().getNotificationSettings { settings in
            guard settings.authorizationStatus == .authorized else { return }
          
            DispatchQueue.main.async {
                // Register the device to receive remote notifications
                UIApplication.shared.registerForRemoteNotifications()
            }
        }
    }
}
```

```objectivec theme={null}
- (void)registerForNotifications {
    // Set delegate to handle push notification further
    [UNUserNotificationCenter currentNotificationCenter].delegate = self;
  
    // Get the user’s permission to show notifications
    UNNotificationPresentationOptions options = UNNotificationPresentationOptionSound | UNNotificationPresentationOptionBadge | UNNotificationPresentationOptionAlert;
    [[UNUserNotificationCenter currentNotificationCenter] requestAuthorizationWithOptions:options completionHandler:^(BOOL granted, NSError * _Nullable error) {
        if (!granted) {
          return;
        }
        
        [[UNUserNotificationCenter currentNotificationCenter] getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) {
            if (settings.authorizationStatus != UNAuthorizationStatusAuthorized) {
              return;
            }
          
            dispatch_async(dispatch_get_main_queue(), ^{
                // Register the device to receive remote notifications
                [[UIApplication sharedApplication] registerForRemoteNotifications];
            });
        }];
    }];
}
```

Call this method in [application(\_:didFinishLaunchingWithOptions:)](https://developer.apple.com/documentation/uikit/uiapplicationdelegate/1622921-application)\
Add this line just before return:

```swift theme={null}
registerForNotifications()
```

```objectivec theme={null}
[self registerForNotifications];
```

### Handling push notifications

You AppDelegate need to use [UNUserNotificationCenterDelegate](https://developer.apple.com/documentation/usernotifications/unusernotificationcenterdelegate) to receive a push notification.\
This class was already assigned as [UNUserNotificationCenter](https://developer.apple.com/documentation/usernotifications/unusernotificationcenter) delegate above.\
Add the following code for `Swift` or extend the class in the case of `Objective-C`:

```swift theme={null}
extension AppDelegate: UNUserNotificationCenterDelegate {
  
}
```

```objectivec theme={null}
@interface AppDelegate() <UNUserNotificationCenterDelegate>
```

Now you have to implement the following functions:

#### Handling push notifications interaction

Use a following [function](https://developer.apple.com/documentation/usernotifications/unusernotificationcenterdelegate/1649501-usernotificationcenter) to handle user tapping on the push notification

```swift theme={null}
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
    completionHandler()
}
```

```objectivec theme={null}
- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)(void))completionHandler {
    completionHandler();
}
```

#### Handling push notifications in foreground

In case you need your app to show a push notification in [foreground](https://developer.apple.com/documentation/uikit/app_and_environment/managing_your_app_s_life_cycle), add this [function](https://developer.apple.com/documentation/usernotifications/unusernotificationcenterdelegate/1649518-usernotificationcenter):

```swift theme={null}
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    completionHandler([.alert, .badge, .sound])
}
```

```objectivec theme={null}
- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler {
    UNNotificationPresentationOptions options = UNNotificationPresentationOptionSound | UNNotificationPresentationOptionBadge | UNNotificationPresentationOptionAlert;
    completionHandler(options);
}
```

Your App is configured for working with push notifications now.\
Let's prepare [notifications for Qonversion Automations](/docs/handling-push-notifications-on-device)

## Android Push Notifications

### Notification types

Firebase Cloud Messaging offers two <a href="https://firebase.google.com/docs/cloud-messaging/concept-options#notifications_and_data_messages" target="_blank" rel="noopener">message types</a>: data messages and notification messages. Qonversion uses data messages to send push notifications on Android. This allows handling notifications in the foreground and background app states and defining what happens upon notifications being pressed.

### Handling push notifications

#### 1 Create a notification channel

You have to register your app's <a href="https://developer.android.com/training/notify-user/channels#CreateChannel" target="_blank" rel="noopener">notification channel</a> in the system to deliver notifications on Android 8.0 and higher.

#### 2 Create a service

Create a service that extends <a href="https://firebase.google.com/docs/reference/android/com/google/firebase/messaging/FirebaseMessagingService" target="_blank" rel="noopener">FirebaseMessagingService</a> to receive and handle notifications from Firebase.

> 📘 AndroidManifest.xml
>
> Don't forget to include YourFirebaseMessagingService in the manifest file.

#### 3 Create and show notifications

Override the <a href="https://firebase.google.com/docs/reference/android/com/google/firebase/messaging/FirebaseMessagingService#public-void-onmessagereceived-remotemessage-message" target="_blank" rel="noopener">onMessageReceived()</a> method to create and show notifications. Provide the channel id, set the <a href="https://developer.android.com/training/notify-user/build-notification#builder" target="_blank" rel="noopener">notification content</a> you want and finally show the notification with `NotificationManagerCompat.notify()`.

> 📘 The code below is just an example for displaying a notification. You can edit it according to your needs. You can also check the official Android push notifications <a href="https://developer.android.com/training/notify-user/build-notification#SimpleNotification" target="_blank" rel="noopener">documentation</a>.

```java theme={null}
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    super.onMessageReceived(remoteMessage);

    String title = remoteMessage.getData().get("title");
    String body = remoteMessage.getData().get("body");
  
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, CHANNEL_ID)
            .setContentTitle(title)
            .setContentText(body)
      		.setSmallIcon(R.drawable.ic_notification);

    NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
    // For notificationId use any unique value you want to be an ID for the notification. 
    notificationManager.notify(notificationId, notificationBuilder.build());
}
```

```kotlin theme={null}
override fun onMessageReceived(remoteMessage: RemoteMessage) {
    super.onMessageReceived(remoteMessage)
      
    val title = remoteMessage.data["title"]
    val body = remoteMessage.data["body"]
      
    // Create a notification
    val notificationBuilder = NotificationCompat.Builder(this, CHANNEL_ID)
        .setContentTitle(title)
        .setContentText(body)
        .setSmallIcon(R.drawable.ic_notification)

    with(NotificationManagerCompat.from(this)) {
        // For notificationId use any unique value you want to be an ID for the notification. 
        notify(notificationId, notificationBuilder.build())
    }
}
```

## Cross-platform Push Notifications

Cross-platform frameworks provide various solutions for implementing push notifications. The concrete implementation depends on the solution you choose for your product. Thus we can not provide any code examples here. Please, visit corresponding tutorials for your cross-platform framework.
