ios - 试验 Firebase - 推送通知

标签 ios swift firebase push-notification firebase-cloud-messaging

为了尝试使用 Firebase 推送通知,我遵循以下示例: https://github.com/firebase/quickstart-ios/blob/dc2cd2db6e82e5c475fa3f0efe75df8b54f04544/messaging/MessagingExampleSwift/AppDelegate.swift#L40-L55

我可以让它工作到一定程度。

这是我的相关代码:

......

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()
}

......

当我尝试测试它时,函数 userNotificationCenter:didReceive:withCompletionHandler() 是唯一被调用的函数(在示例提供的函数列表中)。还应该注意的是,我可以在调试器控制台中看到这一点,但设备上没有任何反应。我想这就是它应该的方式(所以一切都很好),但这里有一个问题我想问任何可以回答的人。

如何使用completionHandler()? 我想,因为它是一个参数,所以我可以以相当自由的方式使用它,但是当我在网上查找示例代码时,我只能看到它在参数列表中声明或按照示例中的情况调用我正在使用它,但我从未见过它的定义。

有什么我应该看的东西或者如何使用它的具体示例吗?

仅供引用,我使用的是 Xcode 版本 10.1、iOS 12.1 和 Swift 4.2。

最佳答案

正如 Apple documentation 中所述,该方法中的completionHandler是:

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.

因此,您应该在处理完通知后调用完成处理程序。您不能以任何其他方式使用它。一旦您调用它,系统就会知道您已完成通知并可以执行任何所需的过程,例如将通知放入用户的通知中心。

关于ios - 试验 Firebase - 推送通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53512234/

相关文章:

ios - 将 iOS 9 今天的扩展程序转换为 iOS 10 的大小问题

firebase - 在将用户添加到 Firebase 时从 Go 管理后端获取消息 token ,在 Javascript 中注册时结束

javascript - 在 Phonegap 中以编程方式加载 Admob 插页式广告

objective-c - 如何在 View Controller 中获取对 UITableView 的引用?

ios - 等待地理编码循环完成

ios - 子类 Crashlytics

javascript - Firestore where 语句与 array-contains 不起作用

javascript - Google Firebase : snap. val().username 返回未定义

iphone - 用于内存管理的 dealloc 与 ViewDidDissapear

iphone - 在 iTunes Connect 中进行应用内购买。如何进行应用内购买 "Cleared for sale"?