How to Add Push Notifications into an iOS App
Tags: mobiledev, ios, swift
Published: 2022-04-01 23:59:20

---
title: How to Add Push Notifications into an iOS App
published: true
date: 2022-03-14 18:36:55 UTC
tags: mobiledev, ios, swift
canonical_url: https://onesignal.com/blog/how-to-add-push-notifications-into-an-ios-app/
---

 ![How to Add Push Notifications into an iOS App](https://onesignal.com/blog/content/images/2022/03/how-to-add-push-notifications-into-ios-app.jpg)

Push Notifications are a great tool to engage and retain your users. In this tutorial, we’ll show you how to add push notifications to your iOS app for free using OneSignal.

### Guide Overview

- [Creating an Apple iOS Push Certificate](#creating-an-apple-ios-push-certificate)
- [Setting up Your OneSignal Account](#setting-up-your-onesignal-account)
- [Setting up Push Notification in iOS](#setting-up-push-notifications-in-ios)
- [Linking an External User ID to the OneSignal Player ID](#linking-an-external-user-id-to-the-onesignal-player-id)
- [Allowing Notifications](#allowing-notifications)
- [Sending Notificaitons](#sending-notifications)

## Getting Started

First off, let’s create an Xcode project as a demo in order to use the SDK. This is going to be an UIKit app, but you can use SwiftUI as well.

![How to Add Push Notifications into an iOS App](https://onesignal.com/blog/content/images/2022/03/Create-a-new-Xcode-project.png)

## Creating an Apple iOS Push Certificate

Before sending push notifications, you'll need to generate an iOS Push Certificate. To do that, you'll need to ask Apple to give you a production certificate. Go to the [developer portal](https://idmsa.apple.com/IDMSWebAuth/signin?appIdKey=891bd3417a7776362562d2197f89480a8547b108fd934911bcbea0110d07f757&path=%2Faccount%2F&rv=1), click on **_Certificates, IDs & Profiles_** , and then click on **_Identifiers_**. Look for the app ID you just created in Xcode. If you can’t find it, click on the **+** button in order to add it.

![How to Add Push Notifications into an iOS App](https://onesignal.com/blog/content/images/2022/03/iOS-push-certificate.png)
_Locate your app ID or add it by clicking the "+" button_

On the _ **Identifiers** _ and **_Profiles_** page, the _App IDs_ option should already be selected. Simply click on the _ **Continue** _ button and you’ll be redirected to the type of app you want to create the ID for. Click on **_Continue_** once again.

![How to Add Push Notifications into an iOS App](https://onesignal.com/blog/content/images/2022/03/iOS-push-certificate-2.png)
_Check that "App IDs" is selected before pressing continue._

Now you’ll land on the App ID registration page where you’ll see two form fields for **_Description_** and **_Bundle ID_**. Fill them with the correct information, being sure that the **_Bundle ID_** exactly matches the one you create previously in Xcode.

![How to Add Push Notifications into an iOS App](https://onesignal.com/blog/content/images/2022/03/iOS-push-certificate-3.png)
_Enter an app "Description" and "Bundle ID."_

Once you click the _ **Continue** _ button, you should see a review page. Click on _ **Register** _ and voilà — you should now see your app in the _ **Identifiers** _ list.

![How to Add Push Notifications into an iOS App](https://onesignal.com/blog/content/images/2022/03/ios-push-certificate-4.png)
_Click "Register" to register your app._

![How to Add Push Notifications into an iOS App](https://onesignal.com/blog/content/images/2022/03/ios-push-certificate-5.png)
_Your app is now viewable from the Identifiers menu._

Next, you'll need to generate a certificate for OneSignal. To do so, open the **_Keychain Access_** app, select **_Certificate Assistant_** from the drop-down menu, and click on **_Request a Certificate From a Certificate Authority_**. This option just means that your machine is going to be the one with the private key for this particular certificate.

![How to Add Push Notifications into an iOS App](https://onesignal.com/blog/content/images/2022/03/keychain-access-certificate.png)
_Select "Certificate Assistant" and "Request a Certificate From a Certificate Authority."_

A window should appear asking you to provide certificate information. Enter your email address and check the _ **Save to disk** _ option. You will also be prompted to choose where you want to save the certificate request. Make sure to save it somewhere safe.

![How to Add Push Notifications into an iOS App](https://onesignal.com/blog/content/images/2022/03/certificate-assistant-apple.png)

Now, you'll need to go back to Apple's developer portal and create a certificate. To do so, click on the **_+_** button.

![How to Add Push Notifications into an iOS App](https://onesignal.com/blog/content/images/2022/03/ios-push-certificate-6.png)

You’ll be redirected to the _ **Certificates** _ creation page. Scroll down on this page until you see the Services header. Under this header, select the option entitled _**Apple Push Notification service SSL (Sandbox & Production)**_ and then click the _ **Continue** _ button.

![How to Add Push Notifications into an iOS App](https://onesignal.com/blog/content/images/2022/03/Apple-push-notification-service-SSL.png)

On the next page, it’ll ask you for the App ID that you want to create the certificate for. Select the one you created earlier from the drop-down menu and click the _ **Continue** _ button.

![How to Add Push Notifications into an iOS App](https://onesignal.com/blog/content/images/2022/03/ios-push-certificate-7.png)
_Select your App ID to create a new Apple Push Notification certificate._

Next, you’ll be prompted to upload the Certificate Signing Request. Choose the file you saved previously and click _ **Continue**._

![How to Add Push Notifications into an iOS App](https://onesignal.com/blog/content/images/2022/03/ios-push-certificate-8.png)
_Upload your Certificate Signing Request._

If everything works just fine, you should be redirected to the download page. Click on the _ **Download** _ button to download it and double-click to open it in the **_Keychain Access_** app.

![How to Add Push Notifications into an iOS App](https://onesignal.com/blog/content/images/2022/03/ios-push-certificate-9.png)
_Download your push notification certificate._

In the _ **Keychain Access** _ app, navigate to the _ **My Certificates** _ tab and find the certificate you just create which has your app bundle ID in the name. Right-click on it to see the options, then click _ **Export** _ from the menu that appears_._ It’ll prompt you to provide the location of the certificate. Select somewhere on your machine and type a password for the certificate.

![How to Add Push Notifications into an iOS App](https://onesignal.com/blog/content/images/2022/03/keychain-access-certificate-1.png)

## Setting Up Your OneSignal Account

In order to add push notifications to your iOS app, you'll need to have a OneSignal account. If you don't have a OneSignal account, you can easily [create a free account](https://app.onesignal.com/signup) or simply [log in](https://app.onesignal.com/login) to an existing account to get started.

### iOS Configuration

In the OneSignal dashboard, click on the _ **New App/Website** _ button.

![How to Add Push Notifications into an iOS App](https://onesignal.com/blog/content/images/2022/03/OneSignal-create-new-app-website.png)
_Configure a new app/website in OneSignal._

On the next page, type the name of your app and select the _**Apple iOS (APNs)**_ option for the platform and click on the _ **Next: Configure Your Platform** _ button.

![How to Add Push Notifications into an iOS App](https://onesignal.com/blog/content/images/2022/03/OneSignal-iOS-setup.png)
_Select Apple iOS (APNs) as your chosen platform._

You’ll be prompted to upload the Apple certificate file you created in the first part of this tutorial. Locate the certificate on your machine, type in the password for the certificate, then click the _ **Save & Continue** _ button.

![How to Add Push Notifications into an iOS App](https://onesignal.com/blog/content/images/2022/03/OneSignal-Apple-iOS-configuration.png)
_Upload your Apple push notification certificate._

Next, you'll be prompted to choose your target SDK. Select **_Native iOS_** as the target SDK and click on _ **Save & Continue** _ button at the bottom of the screen.

![How to Add Push Notifications into an iOS App](https://onesignal.com/blog/content/images/2022/03/OneSignal-Apple-iOS-APNs-select-SDK.png)
_Select Native iOS as your target SDK._

In this final step, under 1. Install the SDK, you should see the App ID provided by OneSignal. Copy it somewhere where it's easy to retrieve — you’ll use it in the code later. Once you've saved the ID, you can click on _ **Done** _.

![How to Add Push Notifications into an iOS App](https://onesignal.com/blog/content/images/2022/03/OneSignal-Apple-iOS-install-SDK.png)

Congratulations, you’ve successfully configured your OneSignal project and you’re almost ready to send your first push notification 🥳 ! The last step is to go back to our iOS project and configure it so that it can receive notifications from OneSignal.

## Setting up Push Notifications in iOS

Go back to the iOS project you created earlier and select the main target. Under the **_Signing & Capabilities_** tab, click on the **_+ Capability_** button, then select **_Push Notifications._** This will enable your app to receive push notifications from OneSignal.

![How to Add Push Notifications into an iOS App](https://onesignal.com/blog/content/images/2022/03/OneSignal-demo-iOS-setup.png)

Next, you'll need to add a Notification Extension to the app. Go back to the **_General_** tab and click the plus icon at the bottom of the **_Targets_** section.

![How to Add Push Notifications into an iOS App](https://onesignal.com/blog/content/images/2022/03/OneSignal-demo-iOS-setup-2.png)

You’ll be prompted to select the template for your new target. Select _ **Notification Service Extension** _ then click _ **Next**._

![How to Add Push Notifications into an iOS App](https://onesignal.com/blog/content/images/2022/03/OneSignal-demo-iOS-setup-3.png)

In the next window, use _ **OneSignalNotificationServiceExtension** _ as the name of the extension (as the docs suggest) and click the _ **Finish** _ button.

![How to Add Push Notifications into an iOS App](https://onesignal.com/blog/content/images/2022/03/OneSignal-demo-iOS-setup-4.png)

A message will appear asking if you want to activate the scheme. You don’t want to activate the push notification scheme because you just want to run your application (not the notification), so click on the **_Cancel_** button.

![How to Add Push Notifications into an iOS App](https://onesignal.com/blog/content/images/2022/03/Activate-OneSignal-notification-service-extension.png)

The notification extension will come with a `NotificationService.swift`_._ Open it and replace the content with the code below:

```
import OneSignal
import UserNotifications

class NotificationService: UNNotificationServiceExtension {
    var contentHandler: ((UNNotificationContent) -> Void)?
    var receivedRequest: UNNotificationRequest!
    var bestAttemptContent: UNMutableNotificationContent?
    
    override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
        self.receivedRequest = request
        self.contentHandler = contentHandler
        self.bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent)
        
        if let bestAttemptContent = bestAttemptContent {   
            OneSignal.didReceiveNotificationExtensionRequest(self.receivedRequest, with: bestAttemptContent, withContentHandler: self.contentHandler)
        }
    }
    
    override func serviceExtensionTimeWillExpire() {
        if let contentHandler = contentHandler, let bestAttemptContent = bestAttemptContent {
            OneSignal.serviceExtensionTimeWillExpireRequest(self.receivedRequest, with: self.bestAttemptContent)
            contentHandler(bestAttemptContent)
        }
    }  
}
```

If you build the project, you’ll get a compilation error since the project doesn’t yet know the OneSignal module. To fix that error, you'll need to install the module via Swift Package Manager.

In Xcode, go to _ **File** _ > _ **Add Packages** _ and enter the package URL  [https://github.com/OneSignal/OneSignal-XCFramework](https://github.com/OneSignal/OneSignal-XCFramework) and click on **_Add Package_**.

![How to Add Push Notifications into an iOS App](https://onesignal.com/blog/content/images/2022/03/Add-packages-in-Xcode.png)
_Add the OneSignal XCFramework in Xcode._

This will add the OneSignal library to the main target. You also need to add the OneSignal library to the extension target. Select the `OneSignalNotificationServiceExtension` target. Under the **_Frameworks and Libraries_** section, click on the _ **+** _ button.

![How to Add Push Notifications into an iOS App](https://onesignal.com/blog/content/images/2022/03/Frameworks-and-Libraries-Xcode.png)
_Add the OneSignal library to the extension target in Xcode. _

After clicking on the + button, a menu should appear. The OneSignal library should be one of the choices in this list. Select **_OneSignal_** and click _ **Add**._

![How to Add Push Notifications into an iOS App](https://onesignal.com/blog/content/images/2022/03/Add-OneSignal-library-Xcode.png)

If you build and run, the error should have disappeared.

![How to Add Push Notifications into an iOS App](https://onesignal.com/blog/content/images/2022/03/OneSignal-build-succeeded-Xcode.png)
_Build Succeeded message in Xcode._

There's one last step you must complete to finish the setup process: configuring the SDK inside your `AppDelegate`. To do so, open your `AppDelegate`, import the OneSignal library, and paste the following initialization code to `didFinishLaunchingWithOptions`:

```
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    
    OneSignal.setLogLevel(.LL_VERBOSE, visualLevel: .LL_NONE)
    
    OneSignal.initWithLaunchOptions(launchOptions)
    OneSignal.setAppId("YOUR_ONESIGNAL_APP_ID")
    
    OneSignal.promptForPushNotifications(userResponse: { accepted in
      print("User accepted notifications: \(accepted)")
    })
    
    return true
  }
```

In this code snippet, you'll need to provide the App ID OneSignal generated for you earlier. You can find this information in your project’s dashboard under the _ **Keys & IDs** _ menu. Because this is sensitive data, make sure to obscure it in some way so that it isn’t visible directly in the source code.

## Linking an External User ID to the OneSignal Player ID

OneSignal creates and stores device and channel level data under a unique OneSignal ID called the `player_id`. A single user can have multiple `player_id` records based on how many devices, email addresses, and phone numbers they use to interact with your app or website.

Create a method that generates a random string as your external user ID and register it to OneSignal. Your final `AppDelegate` should look like this:

```
import UIKit

@main
class AppDelegate: UIResponder, UIApplicationDelegate {

  func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    initializeOneSignal()
    setupExternalId()
    
    return true
  }
  
  private func initializeOneSignal() {
    OneSignal.setLogLevel(.LL_VERBOSE, visualLevel: .LL_NONE)
    
    OneSignal.initWithLaunchOptions(launchOptions)
    OneSignal.setAppId("YOUR_ONESIGNAL_APP_ID")
    
    OneSignal.promptForPushNotifications(userResponse: { accepted in
      print("User accepted notifications: \(accepted)")
    })
  }
  
  private func setupExternalId() {
    let externalUserId = randomString(of: 10)
  
    OneSignal.setExternalUserId(externalUserId, withSuccess: { results in
      print("External user id update complete with results: ", results!.description)
      if let pushResults = results!["push"] {
        print("Set external user id push status: ", pushResults)
      }
      if let emailResults = results!["email"] {
        print("Set external user id email status: ", emailResults)
      }
      if let smsResults = results!["sms"] {
        print("Set external user id sms status: ", smsResults)
      }
    }, withFailure: {error in
      print("Set external user id done with error: " + error.debugDescription)
    })
  }
  
  
  private func randomString(of length: Int) -> String {
    let letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
    var s = ""
    for _ in 0 ..< length {
      s.append(letters.randomElement()!)
    }
    return s
  }
}
```

## Allowing Notifications

The moment of truth has arrived — it's time to put your setup work to the test by sending a notification. To begin, launch your app directly on your iOS device. You should see the following prompt appear asking if you would like to receive notifications from your app. Click on the blue **_Allow_** button to enable push notifications on your device.

![How to Add Push Notifications into an iOS App](https://onesignal.com/blog/content/images/2022/03/OneSignal-Demo-iphone-notification-prompt-1.png)

## Sending Notifications

It’s now time to send your first push notification! To do so, login to your OneSignal account and navigate to the _ **Dashboard** _ tab. On the Dashboard page, click on the blue button at the top right corner entitled +_ **New Push** _.

![How to Add Push Notifications into an iOS App](https://onesignal.com/blog/content/images/2022/03/OneSignal-Dashboard-create-new-push.png)
_Click the "+New Push" button to create a new notification._

You will be redirected to a new window that will allow you to create and customize your push notification.

Under the section entitled _ **Audience** _, make sure that _ **Send to Subscribed Users** _ is selected. Then, create your message by adding your message title, content, and image. Because this is the first notification your subscribers will receive, you may choose to craft a simple welcome message to confirm that they've been subscribed and reinforce the value that notifications will provide.

Under the _ **Delivery Schedule** _ section, select _ **Immediately** _ and _ **Send to everyone at the same time** _ to send to all your current push subscribers. If you have just finished setting up your OneSignal account, chances are you're the first and only subscriber. If your app is heavily trafficked and other users have already opted in to receive push notifications, you may want to select _**Send to a particular segment(s)**_ to test your message out on a select audience. When you're ready to send your message, click on the blue _ **Review and Send** _ button at the bottom of the screen.

![How to Add Push Notifications into an iOS App](https://onesignal.com/blog/content/images/2022/03/OneSignal-dashboard-create-notification-content.png)

A small popup will appear prompting you to review your message. Once you are satisfied, click on the blue _ **Send Message** _ button.

![How to Add Push Notifications into an iOS App](https://onesignal.com/blog/content/images/2022/03/OneSignal-dashboard-review-your-message.png)

You should receive a push notification on your iOS device! 🚀

![How to Add Push Notifications into an iOS App](https://onesignal.com/blog/content/images/2022/03/Push-notification-from-OneSignal-shown-on-iphone-lock-screen.png)

## **Get Support & Share Your Feedback**

To learn more about our iOS mobile push SDK, please visit our iOS push [iOS Mobile Push SDK documentation](https://documentation.onesignal.com/docs/ios-sdk-setup).

We'd love to know what you think and answer any additional questions you have. Ping us on the [OneSignalDevs Discord server](https://discord.com/invite/EP7gf6Uz7G) to share your experience.  We appreciate any insight you can share to help us better serve you!

To stay in the loop with the latest product updates and innovations, follow the [OneSignal Developers Twitter](https://twitter.com/onesignaldevs). For additional support and dev inspiration, tap into our global developer community.

This post was guest authored by **Ibrahima Ciss**