Chapters

Hide chapters

Push Notifications by Tutorials

Fourth Edition · iOS 16 · Swift 5 · Xcode 14

Section I: Push Notifications by Tutorials

Section 1: 15 chapters
Show chapters Hide chapters

3. Remote Notification Payload
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.

As you learned in Chapter 2, “Push Notifications,” a remote push happens by sending data across the internet. That data is referred to as a payload, and it contains all of the information necessary to tell your app what to do when the push notification arrives. The cloud service is responsible for constructing that payload and sending it, along with one or more unique device tokens, to APNs.

Originally, notifications used a packed-binary interface, where each bit of the packet had a specific meaning. Using bitfields is much harder to handle and was confusing for many developers. Apple changed the payload structure and decided to use a single, simple, JSON structure. By using JSON, Apple ensured that the payload is simple to parse and construct in any language, while also providing the flexibility needed for the future, as new capabilities are added to push notifications.

There are a few keys in the JSON payload specifically defined by Apple, some of which are mandatory, but the rest of the keys and values are up to you to define as needed. This chapter will cover those predefined keys.

For regular remote notifications, the maximum payload size is currently 4KB (4,096 bytes). If your notification is too large, Apple will simply refuse it and you’ll get an error from APNs. If you’re suddenly worried that your push notifications won’t work because you’ve got a sizable image to send, for example, don’t worry! You’ll learn how to download attachments in Chapter 10, “Modifying the Payload.”

In this chapter, you’ll learn how to construct the payload, what the various payload keys mean, how to supply custom data and how to handle collapsed and grouped notifications.

The aps Dictionary Key

The aforementioned JSON object is well-structured to hold all of the key pieces of data necessary to describe a push notification. The rest of this chapter will describe each key in detail.

The aps dictionary key is the main hub of the notification payload wherein everything defined and owned by Apple lives. Within the object at this key, you’ll configure such items as:

  • The message to be displayed to the end user.
  • What the app badge number should be set to.
  • What sound, if any, should be played when the notification arrives.
  • Whether the notification happens without user interaction.
  • Whether the notification triggers custom actions or user interfaces.

There are several keys you can use, each with their own considerations.

Setting the Alert

The key you’ll use most often is the alert key. This key allows you to specify the message that will be displayed to your user. When push notifications were first released, the alert key simply took a string with the message. While you can, for legacy reasons, continue to set the value to a string, it’s preferred that you instead use a dictionary. The most common payload for a message would include a simple title and body:

{
  "aps": {
    "alert": {
      "title": "Your food is done.",
      "body": "Be careful, it's really hot!"
    }
  }
}

Localizing Notifications

Yes, the localization monster rears its ugly head, again! If the whole world could just agree on a single language, life would be so much simpler for us developers. You can quickly tell how using a dictionary isn’t going to work for your non-English speaking users. There are two options to work around this issue:

{
  "aps": {
    "alert": {
      "title-loc-key": "FOOD_ORDERED",
      "loc-key": "FOOD_PICKUP_TIME",
      "loc-args": ["2022-05-02T19:32:41Z"]
    }
  }
}

Grouping Notifications

Starting with iOS 12, adding the thread-id key to the aps dictionary will let iOS combine all notifications with the same identifier value into a single group in the notification center. Try to use a guaranteed unique value representing some thread of messages, such as the primary key from a database or a UUID.

{
  "aps": {
    "alert": {
      "title": "Your food is done.",
      "body": "Be careful, it's really hot!",
    },
    "thread-id": "casserole-12345"
  }
}

Adding a Badge

Since your users might not have had their phones handy when the alert message came through, you can also badge the app icon. The badge is the numeric value in a small red circle at the corner of the app icon on the home screen. If you’d like your app icon to display the numerical badge number, simply specify it using the badge key. To clear the badge and remove it, set the value to 0.

{
  "aps": {
    "alert": {
        "title": "Your food is done.",
        "body": "Be careful, it's really hot!"
    },
    "badge": 12
  }
}

Adding Sound

When alerts arrive, it’s possible to have a notification sound play. The most common value is simply the string default, which tells iOS to play the standard alert sound. If you want to use a custom sound included in your app’s bundle, you can instead specify the name of a sound file in your app’s main bundle.

afconvert -f caff -d LEI16 filename.mp3 filename.caf
{
  "aps": {
    "alert": {
        "title": "Your food is done.",
        "body": "Be careful, it's really hot!"
    },
    "sound": "filename.caf"
  }
}

Critical Alert Sounds

If your app needs to display a critical alert, which will be discussed in Chapter 4, “Xcode Project Setup,” you’ll need to use a dictionary as the value of the sound key, instead of just a string:

{
  "aps": {
    "alert": {
        "title": "Your food is done.",
        "body": "Be careful, it's really hot!"
    },
    "badge": 12,
    "sound": {
      "critical": 1,
      "name": "filename.caf",
      "volume": 0.75
    }
  }
}

Other Predefined Keys

Apple defines a few other keys as part of the aps dictionary, which will be discussed in greater detail in later chapters. These can be used for background update notifications, custom notification types, user interfaces and groupings of notifications.

Adding Custom Data

Everything outside of the aps key is for your personal use. You’ll frequently find that you need to pass extra data to your app along with a push notification, and this is where you can do so. For example, if you’re writing a geocaching app, you might want to send the user the next set of coordinates to investigate. You will, therefore, send a payload like so:

{
  "aps": {
    "alert": {
      "title": "Save The Princess!"
    }
  },
  "coords": {
    "latitude": 37.33182,
    "longitude": -122.03118
  }
}

Sending HTTP Headers

As discussed earlier, the payload is only one of a few things your server sends to APNs. Aside from a unique device token, you can send additional HTTP header fields to specify how Apple should handle your notification and how it is delivered to the user’s device. It’s unclear why Apple chose to place these as headers, instead of part of the payload.

Collapsing Notifications

One of those headers is the apns-collapse-id HTTP header field. Apple gives you the ability to collapse multiple notifications down to one when a newer notification supersedes an older one.

Setting the Push Type

As of iOS 13 you are required to specify, in the headers, what type of push notification is being sent. You should specify a value of alert when the delivery of your notification displays an alert, plays a sound or updates the badge. For silent notifications that do not interact with the user you instead specify the value of background.

Adding Priority

The third header you’re likely to use is apns-priority. The default, if not specified, is 10. Specifying a priority of 10 will send the notification immediately, but is only appropriate for notifications which include an alert, sound or badge update.

Key Points

In this chapter, you covered the basics of the remote notification payload. Some key things to remember:

Where to Go From Here?

If you want to learn more about notification payloads, you might be interested in reviewing Apple’s documentation about Generating a Remote Notification. For information on sending notification requests to APNs, including other headers and status codes, refer to Apple’s Sending Notification Requests to APNs webpage.

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.
© 2024 Kodeco Inc.

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 Kodeco Personal Plan.

Unlock now