Home iOS & Swift Books Push Notifications by Tutorials

4
Xcode Project Setup Written by Scott Grosch

Heads up... You're reading this book for free, with parts of this chapter shown beyond this point as scrambled text.

You can unlock the rest of this book, and our entire catalogue of books and videos, with a raywenderlich.com Professional subscription.

Before you start sending and receiving push notifications, you first need to make sure your project is set up to do so!

Open Xcode and create a new iOS App project. Select SwiftUI as the Interface and SwiftUI App for the Life Cycle. You may leave the checkmarks at the bottom of the project creation screen unchecked, as you won’t need Core Data or any tests in your project. In the Bad Ol’ Days, this is the point in which you’d have to set up a custom profile with Apple to enable push notifications. Fortunately, with the current toolchains, this is all automated now.

Adding capabilities

To tell Xcode that you’ll be using push notifications in this project, just follow these four simple steps so that it can handle the registration for you:

  1. Press + 1 (or View ▸ Navigators ▸ Project) to open the Project Navigator and click on the top-most item (i.e. your project).
  2. Select the target, not the project.
  3. Open the Signing & Capabilities tab.
  4. Click the + Capability button.
  5. Search for and select Push Notifications from the menu that pops up. If you don’t see the Push Notifications capability, you’re not using a paid Apple Developer account. Double-check that you selected the correct Team and check that you have a valid Provisioning Profile for your team and bundle ID.
  6. Notice the Push Notifications capability added below your signing information.

If you were to go back to the Member Center now and look at your provisioning profiles, you’d see that one has been generated specifically for this project with push notifications enabled. Well, that was so easy that it makes you wonder why Apple didn’t make it this easy from day one!

Registering for notifications

You’ve told Apple that you’re going to use push notifications. Next, you’ll have to add the required code to prepare your app for receiving push notifications. As push notifications are an opt-in feature, you’ll have to request permissions from the user to enable them.

import UIKit
import UserNotifications

class AppDelegate: NSObject, UIApplicationDelegate {
  func application(_ application: UIApplication,
                   didFinishLaunchingWithOptions launchOptions:
                        [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    UNUserNotificationCenter.current().requestAuthorization(options: [
      .badge, .sound, .alert
    ]) { granted, _ in
      guard granted else { return }

      DispatchQueue.main.async {
        application.registerForRemoteNotifications()
      }
    }

    return true
  }
}
@UIApplicationDelegateAdaptor(AppDelegate.self)
private var appDelegate

Provisional authorization

An alert like the one above can be somewhat jarring to a user when the app starts up the first time. Why are they being asked for this? What type of data are you going to send? If you talk to your friends and colleagues, you’ll likely find that a surprising number of people, especially older people, simply reject all notifications.

Critical alerts

There’s another type of authorization that you might need to request, depending on the type of app you’re building. If your app has something to do with health and medicine, home security, public safety or anything else that may have the need to present a notification even if the user declined alerts, you can ask Apple to configure critical alerts via the .criticalAlert enum case. Critical alerts will bypass Do Not Disturb and ringer switch settings as well as always play a sound… even a custom sound.

Getting the device token

If your app successfully registered for notifications, iOS will call another delegate method providing a device token to your app. The token is an opaque data type which is globally unique and identifies one app-device combination with the APNs.

func application(
  _ application: UIApplication, 
  didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
  let token = deviceToken.reduce("") { $0 + String(format: "%02x", $1) }
  print(token)
}

func application(
  _ application: UIApplication,
  didFailToRegisterForRemoteNotificationsWithError error: Error) {
  print(error)
}

Key points

  • You must tell Xcode that push notifications will be part of your project; follow the steps in this chapter so that Xcode can handle the registration for you.
  • You must add the required code to prepare your app for receiving push notifications.
  • Push notifications are an opt-in feature, so you must request permissions from the user to enable them.
  • To avoid jarring notifications the first time a user opens an app, use provisional authorization so that notifications are delivered silently to the user’s Notification Center, without asking for permission.
  • For critical alerts that override a user’s declined alerts, you must apply for a special entitlement from Apple to enable them, due to their disruptive nature.
  • Once you have successfully registered your app for notifications, iOS will call a delegate method, providing a device token to your app. Never make assumptions about the length of your token or try to link the token to a specific user.
  • Specify in your App struct implementation that you’re using an app delegate.

Where to go from here?

At this point, you’ve technically done everything necessary to make your app capable of receiving and displaying a push notification. In the next chapter, you’ll get your Authentication Token from Apple so that Apple’s servers will allow you to send notifications and you’ll finally send your first push notification!

Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum here.

Have feedback to share about the online reading experience? If you have feedback about the UI, UX, highlighting, or other features of our online readers, you can send them to the design team with the form below:

© 2021 Razeware LLC

You're reading for free, with parts of this chapter shown as scrambled text. Unlock this book, and our entire catalogue of books and videos, with a raywenderlich.com Professional subscription.

Unlock Now

To highlight or take notes, you’ll need to own this book in a subscription or purchased by itself.