DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Pato for OneSignal

Posted on • Originally published at onesignal.com on

How to Add Push Notifications into an iOS App

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.

How to Add Push Notifications into an iOS App

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.

How to Add Push Notifications into an iOS App
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
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
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
Click "Register" to register your app.

How to Add Push Notifications into an iOS 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.

How to Add Push Notifications into an iOS App
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

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

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

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

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.

How to Add Push Notifications into an iOS App
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
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
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
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

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

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

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

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

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

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)
        }
    }  
}
Enter fullscreen mode Exit fullscreen mode

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.

How to Add Push Notifications into an iOS App
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
_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

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

How to Add Push Notifications into an iOS App
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
  }
Enter fullscreen mode Exit fullscreen mode

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
  }
}
Enter fullscreen mode Exit fullscreen mode

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

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

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

You should receive a push notification on your iOS device! πŸš€

How to Add Push Notifications into an iOS App

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.

This post was guest authored by Ibrahima Ciss

Top comments (0)

🌚 Browsing with dark mode makes you a better developer.

It's a scientific fact.