Experimenting with Firebase - Push Notifications

2019-08-17 05:35发布

问题:

In order to try out Push Notifications with Firebase I am following this example: https://github.com/firebase/quickstart-ios/blob/dc2cd2db6e82e5c475fa3f0efe75df8b54f04544/messaging/MessagingExampleSwift/AppDelegate.swift#L40-L55

I could make it work up to a certain point.

Here is the relevant code I have:

......

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    ......
    UNUserNotificationCenter.current().delegate = self
    let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
    UNUserNotificationCenter.current().requestAuthorization(
        options: authOptions,
        completionHandler: {_, _ in })
    application.registerForRemoteNotifications()
    FirebaseApp.configure()
    ......

    return true
}

......

func userNotificationCenter(_ center: UNUserNotificationCenter,
                            didReceive response: UNNotificationResponse,
                            withCompletionHandler completionHandler: @escaping () -> Void) {
    let userInfo = response.notification.request.content.userInfo
    // Print message ID.
    print(#function)
    if let messageID = userInfo[gcmMessageIDKey] {
        print("Message ID: \(messageID)")
    }

    // Print full message.
    print(userInfo)

    completionHandler()
}

......

When I try to test it, the function userNotificationCenter:didReceive:withCompletionHandler() is the only one called (in the list of function provided by the example). It should also be noticed that I can see this looking at the debugger console and nothing is happening on the device. I guess that's the way it's supposed to be (so all is fine), but here is a question I have for anyone who can answer.

How do I make use of completionHandler() ? I suppose, since it's a parameter I can make some use of it in a rather free way, but when I look for sample code on the net I can only see it declared in the list of parameters or called as is the case in the example I am working with, but I never see it defined.

Is there something I should look at or a concrete example of how to make use of it?

For information, I am using Xcode Version 10.1, iOS 12.1 and Swift 4.2.

回答1:

As explained in Apple's documentation, completionHandler in this method is:

The block to execute when you have finished processing the user’s response. You must execute this block at some point after processing the user's response to let the system know that you are done. The block has no return value or parameters.

So you should call completion handler when you are done processing the notification. You cannot use it in any other way. Once you call it, the system then knows you are done with the notification and can perform any needed processes, such as putting the notification in the user's notification center.