Simplifying notifications with the Courier iOS SDK
Tags: mobile, tutorial
Published: 2023-03-23 17:16:58

Push notifications are a valuable tool for keeping users informed and increasing their engagement with your app. You can use push notifications to alert users about promotions, new content, or any other important updates. While push notifications are a powerful tool, setting up push notifications in iOS can be a daunting task that requires a significant amount of effort and time. Fortunately, the Courier iOS Mobile Notifications Software Development Kit (SDK) simplifies this process.

![iOS push notifications with Courier](//images.ctfassets.net/z7iqk1q8njt4/3rUcQDOobYWo1ZWJPFVwnH/d687bb8df008f348d2f18e38f38b091d/Simplifying_Notifications_with_the_Courier_iOS_SDK.png)

The Courier iOS SDK can help you to implement push notifications in iOS apps more easily thanks to some useful tools. The benefits of using the SDK include:
- __Simplified setup process__. The Courier iOS SDK streamlines the process, making it easy to get set up and start sending push notifications. With some easy-to-follow setup steps and a few lines of code, you can quickly integrate the SDK into your apps.
- __Effective management of tokens and user state__. When implementing push notifications, you would normally need to handle token management manually, which involves generating and storing unique identifiers for each device that can receive notifications. This can be complex and time-consuming. The Courier iOS SDK provides tools that enable you to manage tokens and user state effectively.
- __Sending test notifications__. Before sending push notifications to all users, it's important to test that they're working as intended. With the Courier iOS SDK, you can send test notifications to check that your notifications are working as intended before they go live. This can save time and prevent problems later.

## Token management
Managing push notification tokens is a complex task. Let’s talk a bit about how they work, to help us better understand the benefits of the Courier SDK.

Tokens are unique identifiers that are used to identify a specific device for push notifications. They are generated and managed by the push notification service, which is the Apple Push Notification Service (APNS) for iOS. These tokens need to be securely stored on the back end, associated with the relevant user or device, and regularly updated as they can change or expire. Additionally, token management includes handling token deletion when a user unsubscribes from push notifications or uninstalls your app.

Setting up and managing your own token management infrastructure can be a time-consuming and challenging task, requiring collaboration between front-end, mobile, and back-end developers. However, with the Courier iOS SDK, token management is handled automatically. The SDK automatically takes push notification tokens, stores them in Courier, and invalidates tokens that expire, so you can focus on building your product without having to learn the complex logistics of token management.

## Getting started with Courier's iOS SDK
Before you can use the [Courier iOS SDK](https://github.com/trycourier/courier-ios "Courier iOS SDK"), you'll need a few things:
- __[Xcode](https://developer.apple.com/xcode/ "Xcode - Apple Developers")__. You'll need to have Apple's integrated development environment (IDE), Xcode, installed on your computer. 
- __An Apple developer account__. To enable push notifications in your app, you'll need a valid Apple developer account.
- __A physical iOS device__. You'll need an iOS device to test your push notifications.

You can find a full and detailed set-up guide in the iOS docs on the [Courier GitHub repository](https://github.com/trycourier/courier-ios#installation "Courier iOS SDK installation"). 

## Push providers
Before we look at sending a test push notification, it’s worth noting that to enable push notification support you will need to configure a push provider. A push provider is a service that handles the delivery of push notifications to targeted devices, ensuring reliable and efficient message transmission.

Take a look at our [GitHub](https://github.com/trycourier/courier-ios#3-configure-push-provider "Courier iOS SDK") page for more information. There you will find links to APNS (Apple Push Notification Service) and FCM (Firebase Cloud Messaging). Follow the links there to see more detailed information.

## Enabling push notification capability
Another vital step is to enable push notification capability in your iOS app. Here's how to do that.

1. Create a new iOS app ID and a provisioning profile in the Apple Developer portal.
   - Log in to the Apple Developer portal and create a new app ID for your app.
   - Create a new provisioning profile for your app, which will allow it to access push notification services.
2. In Xcode, open your app project and select the project file from the project navigator.
3. Select your app target and click on the "Capabilities" tab.
4. Turn on the "Push Notifications" capability.
5. In the "Signing & Capabilities" tab, select the team for your app and choose the provisioning profile you created in step 1.

Once this is done, you’ll have enabled push notification capability in your iOS app and can start sending push notifications to your users through the Courier iOS SDK.

## Setting up a notification service extension
So that you can better track your notifications, we recommend that you create a notification service extension in your iOS app. 

A notification service extension is a type of iOS app extension that allows developers to track the delivery status of notifications and perform additional actions, such as modifying the content of a notification. 

Setting up this extension allows Courier to accurately tell when your user receives a push notification when they are not using the app.

You can find a full setup guide [here](https://github.com/trycourier/courier-ios#add-the-notification-service-extension-recommended "Courier iOS SDK"), on the Courier iOS SDK GitHub page. It won’t take long, and then Courier will be able to track delivery status in any state your app could be in.

## Push notification permissions
The Courier iOS SDK needs to have push notification permissions granted by your users before it can access the push notification token. That’s where the `requestNotificationPermission()` function comes in.
Here's how it works:

```javascript
if (await Courier.shared.requestNotificationPermission()) 
{ // Send some notification }
 ```

The `requestNotificationPermission()` function returns an authorization status that indicates whether the user has granted or denied permissions for push notifications.

You can read more about authorization status [here](https://developer.apple.com/documentation/usernotifications/unauthorizationstatus "Apple Developer Documentation").

Once your user has given access to receive notifications, a push notification device token is created by iOS and automatically synced to Courier.

## Managing user state
Now that you've set up your notification service extension and handled permissions, it's time to focus on delivering a great user notification experience. One key part of this is keeping track of user state — the status of a user in relation to your app. This allows you to send users appropriate notifications based on whether they’re logged in or out. For instance, if a user is logged out, it wouldn't make sense to send them a notification about an activity that requires them to be logged in. 

The Courier iOS SDK provides tools that help developers manage user state effectively and easily. By using the `signIn()` function provided by the SDK, developers can ensure that the user's push notification tokens and their state are kept in sync. Here's how to use the function:

```javascript
await Courier.shared.signIn(
    accessToken: accessToken,
    userId: userId,
)
```

The `accessToken` can either be a Courier Auth Key used during development or a JWT (JSON Web Token) that should be used in a production app. You can create an access token by calling the Courier API as shown in the GitHub [documentation](https://github.com/trycourier/courier-ios#going-to-production "Courier iOS SDK"). When the user signs out, you can use the `signOut()` function to clear their state.

The `signIn()` function saves the `accessToken` and `userId` to the native-level local storage, ensuring that the user's state persists between app sessions. This ensures that the user's push notification tokens are kept up to date.
By following these steps, you automatically sync push notification tokens and user state to Courier. This lets you ensure that push notifications are delivered at the right time and in the appropriate context for a better user experience.

## Handling notification delivery
We've made it easy for you to monitor the delivery status of your notifications using the Courier iOS SDK via the `onPushNotificationDelivered()` function. 

When a push notification is delivered to a user's device, `onPushNotificationDelivered()` is triggered automatically by the SDK if the app is in foreground. Here is an example implementation of the function in the `AppDelegate` class (the `AppDelegate` class is a key part of every iOS app and handles system-level events, including push notifications):

Courier analytics will track the delivery of this notification for you automatically.

```javascript
class AppDelegate: CourierDelegate {

    override func pushNotificationDeliveredInForeground(message: [AnyHashable : Any]) -> UNNotificationPresentationOptions {
        print(message)
        return [.sound, .list, .banner, .badge] // Pass [] to hide any foreground presentation
    }
}
```

Note that this function will not be triggered when the app is in the "killed", "not running", or “background” state.

## Handling a notification click
The `pushNotificationClicked()` function provided by the Courier iOS SDK can be used to handle user interaction with a notification inside your AppDelegate class. This function is called when the user clicks on a notification that was sent through Courier. Here's sample code for using the function:

Courier analytics will track the clicking of this notification for you automatically.

```javascript
class AppDelegate: CourierDelegate {
  override func pushNotificationClicked(message: [AnyHashable : Any]) {
    print(message)
  }
}
```

In this example, the function simply prints out the content of the message payload. However, you can use the message to perform any number of actions in your app, such as opening a specific screen or executing a certain function. 

## Sending a test push
Now that you’ve set up your push notification infrastructure and know how to manage user state, you can start sending messages. The SDK allows you to send push notifications directly to a user ID without having to juggle tokens or manage a back end.

To send a test push notification, you can use the `sendPush()` function: 

```javascript
let messageId = await Courier.shared.sendPush(
	authKey: "a_courier_auth_key_that_should_only_be_used_for_testing",
	userId: "example_user",
	title: "Happy Holidays!",
	body: "Happy holidays from Courier.",
	providers: [.apns, .fcm],
)
```

Note that your user must have been given access to receive push notifications so that the push notification device tokens can be automatically synced to Courier and Courier can send a message to your user’s device. See “Push notification permissions” above for more details.

## Conclusion
With just a few lines of code, you can streamline your push notification management and focus on building your product, thanks to the Courier iOS SDK.

By taking care of complex tasks such as token management and message delivery tracking, the SDK allows you to focus on building high-quality push notification experiences for your users. 

If you’re an iOS developer, make sure to give the Courier iOS SDK a try and see how it can simplify and enhance your push notification workflow. Courier also has other SDKs available for [Android](https://github.com/trycourier/courier-android "Courier Android SDK"), [React Native](https://github.com/trycourier/courier-react-native "Courier React Native SDK"), and [Flutter](https://github.com/trycourier/courier-flutter "Courier Flutter SDK"). So if you're looking for a way to simplify your push notification management, check out [Courier](https://www.courier.com/ "Powerful Notifications System - Courier") today.