Check your service and support coverage

After has recently reminded about his updating APNs provider API which makes me realised a lot has changed about push notifications, both in terms of client & provider approach.

Bạn đang xem: Check your service and support coverage

The HTTP/2-based Apple Push Notification service (APNs) provider API lets you take advantage of great features, such as authentication with a JSON Web Token, improved error messaging, và per-notification feedbaông chồng. If you skết thúc push notifications with the legacy binary protocol, we strongly recommend upgrading lớn the APNs provider API.

From the the iOS client point of view, you pretty much don’t need khổng lồ care about provider API, as you only need lớn register for push notification capability & send the device token to lớn your backkết thúc, & it’s the backend’s job lớn send push request lớn Apple notifications server.

But it’s good khổng lồ know the underlying mechanism, especially when you want lớn troubleshoot push notification. Since a push notification failure can be because of many reasons: it could be due to some failed logic in your backover, or that the push certificate has expired, or that you have sent the wrong device token, or that user has turned off push permission in Settings phầm mềm, or that the push has been delayed.

Here’s also a common abbreviations you need khổng lồ learn: APNs it is short for Apple Push Notification service. You can think of it as the VPS your device always has connection with, so you're ready for any VPS push messages from it.

What is binary provider API

Push notification feature was first introduced by Apple in 2009 via a fairly complex binary provider API

In short, binary provider API is just a specification about which address và which format to lớn sover push request to Apple push hệ thống. The binary interface of the production environment is available through gateway.push.hãng, port 2195 và development environment gateway.sandbox.push.tá, port 2195. The binary interface employs a plain TCP. socket for binary nội dung that is streaming in nature.

As you can see in the package instruction above sầu, we need specify frame length and data. Data is a key value pairs of multiple informations lượt thích device token, expiration, topic, priority.

Skết thúc request to lớn the above sầu addresses via secured TLS or SSL channel. The SSL certificate required for these connections is obtained from your developer account.

The new HTTP/2 provider API

The new HTTP2/ provider API is recommended, it has detailed error reporting và better throughput. If you use URLSession which supports the HTTP/1.1 và HTTP/2 protocols. HTTP/2 tư vấn, as described by RFC 7540, you will feel familiar.

In short, when you have sầu a notification to lớn sover to lớn a user, your provider must construct a POST request và sover it to lớn Apple Push Notification service (APNs). Your request must include the following information:

The JSON payload that you want khổng lồ sendThe device token for the user’s deviceRequest-header fields specifying how to deliver the notificationFor token-based authentication, your provider server’s current authentication token

Upon receiving your server’s POST request, APNs validates the request using either the provided authentication token or your server’s certificate. If validation succeeds, APNs uses the provided device token lớn identify the user’s device. It then tries to send your JSON payload khổng lồ that device.

So it’s pretty much how you configure URLRequest with URLSession, specify base url, some request headers including the authorization & the payload body toàn thân.

Use HTTP/2 và TLS 1.2 or later to establish a connection to the new provider API endpoint. For development serverit is api.sandbox.push.táo bị cắ và for production VPS it is api.push.táo bị cắn dở.com:443. You then send the request as POST & Apple will vày its job khổng lồ verify and send the push notification to lớn the users device.

Certificate vs token based authentication

To send push request to APNs, you need lớn authenticate lớn tell that is really from you. APNs tư vấn 2 types of authentication, the traditional way with a certificate, & the recently new recommended way with a p8 token.

Certificate based authentication

For certificate based authentication, you will need a p12 certificate which you can obtain và generate from your Developer tài khoản.



Because there are sandbox and production push endpoint, few years ago it was required khổng lồ have separate sandbox và production environment push certificate, which you had to lớn create separately in your Apple developer tài khoản, then in testing need lớn specify the correct push certificate for each environment.

Now around iOS 10 year we can use just 1 single certificate for both sandbox and production, which is a relief for us developers. When we create certificate on Apple developer page, we need to upload a certificate signing request that we can generate from Keychain Access app. After we download the generated push certificate, tải về & run it in Keychain, there we can generate p12 key file that contains both certificate & private key lớn sign our push request.

Certificate and provisioning profiles valid for only 1 year. So every year you have to renew push notification certificates, which is also a good & bad thing. Besides that, every app differs from bundle id, so we kindomain authority have lớn generate certificate for each app.

Token based authentication

Token-based authentication offers a stateless way to communicate with APNs. Stateless communication is faster than certificate-based communication because it doesn’t require APNs to look up the certificate, or other information, related to your provider server. There are other advantages to lớn using token-based authentication:

The cool thing about token is that you can use one token to distribute notifications for all of your company’s apps. You can create in your Apple developer trương mục. Key authentication is the recommended way to lớn authenticate with Apple services, so it is used not only for push services, but also for MusicKit và DeviceCheông xã.

When you request a key, Apple gives you a 10-character string with the Key ID which you must include this string in your JSON tokens and an authentication token signing key, specified as a text tệp tin (with a .p8 file extension). The key is allowed lớn download once and you need to lớn keep it properly.

The token that you include with your notification requests uses the JSON Web Token (JWT) specification. The token itself contains four key-value pairs



After all, the JSON Web Token is encoded in this authorization HTTP. headers in your request like this

authorization = bearer eyAia2lkIjogIjhZTDNHM1JSWDciIH0.eyAiaXNzIjogIkM4Nk5WOUpYM0QiLCAiaWF0I jogIjE0NTkxNDM1ODA2NTAiIH0.MEYCIQDzqyahmH1rz1s-LFNkylXEa2lZ_aOCX4daxxTZkVEGzwIhALvkClnx5m5eAT6 Lxw7LZtEQcH6JENhJTMArwLf3sXwiFor security, APNs requires you lớn refresh your token regularly. Refresh your token no more than once every trăng tròn minutes and no less than once every 60 minutes.

How khổng lồ register for push notifications from iOS app

The APIs to lớn register for remote notification has changed over the years.

iOS 7

In iOS 7, we used to lớn use this method registerForRemoteNotificationTypes lớn register khổng lồ receive remote notifications of the specified types via Apple Push Notification service.

Xem thêm: 2 Lớp Mạng Khác Nhau Vẫn Ping Được, Hỏi/ Thắc Mắc, 2 Lớp Mạng Khác Nhau Vẫn Ping Được

The types can be UIRemoteNotificationTypeBadge, UIRemoteNotificationTypeAlert, UIRemoteNotificationTypeSound

When you send this message, the device initiates the registration process with Apple Push Notification service. If it succeeds, the ứng dụng delegate receives a device token in the application:didRegisterForRemoteNotificationsWithDeviceToken: method; if registration doesn’t succeed, the delegate is informed via the application:didFailToRegisterForRemoteNotificationsWithError: method. If the ứng dụng delegate receives a device token, it should connect with its provider & pass it the token.

iOS 8 with registerUserNotificationSettings

From iOS 8, there’s separation between asking for a remote notification with device token, và with presenting push message to lớn the user. This confused developers as these 2 things are separate now.

First, we use registerForRemoteNotifications khổng lồ register to receive sầu remote notifications via Apple Push Notification service.

Call this method lớn initiate the registration process with Apple Push Notification service. If registration succeeds, the tiện ích calls your phầm mềm delegate object’s application(_:didRegisterForRemoteNotificationsWithDeviceToken:) method and passes it a device token. You should pass this token along to the VPS you use to lớn generate remote notifications for the device. If registration fails, the ứng dụng calls its tiện ích delegate’s application(_:didFailToRegisterForRemoteNotificationsWithError:) method instead.

In short, this is khổng lồ receive device token from APNs so we can bởi silent push notification or other things. Note that we need lớn enable Remote notification capability for Background modes.


To present push message to user via alert, banner, badge or sound, we need khổng lồ explicitly ask for using this method registerUserNotificationSettings to registers your preferred options for notifying the user.

If your ứng dụng displays alerts, play sounds, or badges its icon, you must Điện thoại tư vấn this method during your launch cycle to request permission lớn alert the user in these ways. After calling this method, the app calls the application(_ application: UIApplication, didRegister notificationSettings: UIUserNotificationSettings) method of its app delegate to lớn report the results. You can use that method khổng lồ determine if your request was granted or denied by the user.

iOS 10 with UserNotifications framework

In iOS 10, Apple introduced UserNotifications và UserNotificationsUI framework & lots of new features to push notifications lượt thích actions & attachments.

To ask for permission to lớn present push message from iOS 10, use the new UNUserNotificationCenter which accepts options and bloông chồng callback with grant status.

UNUserNotificationCenter.current().requestAuthorization(options: <.badge, .sound, .alert>)There ‘s also UNNotificationkích hoạt và UNNotificationAttachment khổng lồ specify additional actions & attachment to go along with the push message, this is very handy for visual purpose and convenient actions user can persize right away from the push message.

There’s also a convenient UserNotificationsUI that was shipped with iOS 10 that allows us to lớn embed custom view controller from our push message

When an iOS device receives a notification containing an alert, the system displays the contents of the alert in two stages. Initially, it displays an abbreviated banner with the title, subtitle, and two khổng lồ four lines of body text from the notification. If the user presses the abbreviated banner, iOS displays the full notification interface, including any notification-related actions. The system provides the interface for the abbreviated banner, but you can customize the full interface using a notification nội dung ứng dụng extension.

Also, there is this callbaông xã userNotificationCenter _:willPresent that asks the delegate how khổng lồ handle a notification that arrived while the tiện ích was running in the foreground.

If your app is in the foreground when a notification arrives, the shared user notification center calls this method khổng lồ deliver the notification directly to your ứng dụng. If you implement this method, you can take whatever actions are necessary lớn process the notification or show it when your tiện ích is running.

iOS 12 with provisional push

New in iOS 12 is the UNAuthorizationStatus.provisional, which are notifications that appear silently in the user’s notification center without appearing on the user’s trang chính screen. We can start sending them as soon as a user has downloaded and run your tiện ích for the first time. You can send provisional push notifications unlimited times unless the user explicitly turns them off.

This is good khổng lồ skết thúc unobtrusive push lớn users in their Notification Center where they can pick up at a later time.

Testing push notification in simulator

We have sầu been able to lớn drag images to lớn the Photos phầm mềm in simulator for years, but new in Xcode 11.4 is the ability to drag push payload lớn simulator khổng lồ simulate remote push notification.

All we have to lớn bởi is create an apns file with Simulator Target Bundle key to lớn specify our phầm mềm, then drag lớn the simulator

"Simulator Target Bundle": "com.onmyway133.PushHero", "aps": "alert": "Welcome khổng lồ Push Hero", "sound": "chime", "badge": 2 Many of the simulator features can be controlled via xcrun simctl comm& line tool where you can change status bar time, battery info, start & stop certain simulators & send push with xcrun simctl push. This is very handy in case you want to automate things.

Test push notification easily with Push Hero

As iOS developers who need to lớn kiểm tra push notification a lot, I face this challenge. That’s why I made Push Hero as a native macOS application that allows us to reliably test push notification. It is written in pure Swift with all the new APNs specification in mind.

With Push Hero, we can thiết đặt multiple test scenario for different tiện ích. Each we can specify the authentication method we want, either with p8 token or p12 certificate based. There’s also input đầu vào validation và hint helper that explains which field is needed and in which format, so you save sầu time khổng lồ work on your push testing instead.

New in latest version of Push Hero is the ability lớn send multiple pushes to lớn multiple device tokens, which is the most frequent request. In the right history pane, there’s information about each request & response nội dung, together with apns id information và reason explanation.


Push notification continues khổng lồ be important for iOS apps, & Apple has over the years improved và changed it for the better. This also means lots of knowledge to keep up with. Understanding provider APNs, setting up certificate và JSON Web Token key can be intimidating & take time.

Hopefully the above summary gets you more understanding into push notification, not only the history of changes in both client & provider API, but also some ways lớn thử nghiệm it easily.