Skip to content

Instantly share code, notes, and snippets.

@dakeshi
Last active June 15, 2018 06:58
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dakeshi/4816c9a7f4d3a75bd6cc51595f26d72a to your computer and use it in GitHub Desktop.
Save dakeshi/4816c9a7f4d3a75bd6cc51595f26d72a to your computer and use it in GitHub Desktop.
iOS10 remote push notification

iOS 10 Remote Notification

In iOS 10, there are big changes in the notification. Remote and local notification methods are unified. You can add media such as image using notification extension. In this article, I will talk about how to set up notification types and register the remote notification. And I will show you how to handle remote notification and the actionable notification in the next section.

Remote Notification Process

First, it is helpful to know about how to work remote notification. Remote notification involves the following steps:

  1. Configure your notification types and register the remote notification

  2. Register remote notification to APNs

  3. Register device token to your server (push notification provider)

  4. Communicate between provider and APNs

  5. Handle remote notifications

Note
step 3 and 4 are the server side process.

configure notification types and register the remote notification

configure notification types

You need to request authorization for receiving notifications. In this stage, you can set up notification types such as alert, sound and badge.

In iOS 9 and below

use registerUserNotificationSettings method

In iOS 10

use requestAuthorization(options:completionHandler:) method.

func requestAuthorization(options: UNAuthorizationOptions = [],
        completionHandler: @escaping (Bool, Error?) -> Void)
  • options describe which notification types you want to provide.

  • completionHandler has two parameters: granted and error

    • error is nil if no error occurred.

    • granted returns true or false depends on the following cases:

Cases Return value

Select allow in the authorization request dialog

True

Select don’t allow in the authorization request dialog

False

The notification setting for the app is not enabled

False

The notification setting for the app is enabled but one or more authorization options are disabled

True

It is not results what I expected. Why?

The value of this parameter is true when authorization for the requested options was granted. The value is false when authorization for one or more of the options is denied.

In apple document, they talk about requested options, not the notification setting. But the practical test results are different as you see in the above list. It has not returned false value if users change authorization options such as disabling alert in the setting app.

Note
Authorization request dialog appears only once when you launch your app at the first time. So, I recommend you to set up .alert option as a default. If you omit it from registerUserNotificationSettings or requestAuthorization(options:completionHandler:) , you could not find .alert option in the setting app for your app notification.

register the remote notification

  • call registerForRemoteNotifications() method.

  • If the registration succeeds, it will automatically call application:didRegisterForRemoteNotificationsWithDeviceToken delegate method. If it is failed, application:didFailToRegisterForRemoteNotificationsWithError delegate method is called.

sample code

appDelegate.swift
import UserNotifications

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?


    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    	// 1. registering notification type
        if #available(iOS 10.0, *) {
          UNUserNotificationCenter
          .current()
          .requestAuthorization(options: [.alert, .sound, .badge]) {
            granted, error in

           if granted && error == nil {
             debugPrint("granted")
             // 2. registering your app for remote notifications.
             application.registerForRemoteNotifications()
           } else {
            // Disable the notification service. ex) Notify to provider server.
            debugPrint(error?.localizedDescription ?? "authorization is not granted. check your app notification setting in the setting app")
          }
       } else {
            let settings = UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
            // To call registerForRemoteNotifications safely, use application:didRegister delegate method in iOS9 below
        }
    }
    ...
    ...

@available(iOS, deprecated: 10.0)
extension AppDelegate {
  func application(_ application: UIApplication, didRegister notificationSettings: UIUserNotificationSettings) {
    application.registerForRemoteNotifications()
  }
}

Register remote notifications to APNs

If you register your remote notification successfully to APNs,

Handle remote notifications

  • foreground

  • background or the app is closed

  • In iOS 10

    • userNotificationCenter(_:willPresent:withCompletionHandler:) is called when the app is the foreground state

    • use userNotificationCenter(_:didReceive:withCompletionHandler:) to deal with actionable notifications when the app is the background or closed state.

  • custom actions

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment