How to Add Push Notifications into an iOS App

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

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.

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, 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.

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.

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.

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.

Click "Register" to register your app.
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.

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.

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

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.

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.

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.

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.

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.

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 or simply log in to an existing account to get started.

iOS Configuration

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

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.

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.

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.

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.

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.

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.

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

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

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.

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 and click on Add Package.

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.

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.

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

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.

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.

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.

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

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

Get Support & Share Your Feedback

To learn more about our iOS mobile push SDK, please visit our iOS push iOS Mobile Push SDK documentation.

We'd love to know what you think and answer any additional questions you have. Ping us on the OneSignalDevs Discord server 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. For additional support and dev inspiration, tap into our global developer community.

Join our Developer Community

This post was guest authored by Ibrahima Ciss.