我正在创建一个 iOS 项目,该项目将使用 Firebase 云消息传递 (FCM) 将自定义数据元素通过 Firebase/APNS 通知从公司服务器发送到 iOS 设备。
我首先要了解的是,与 Android 不同,没有类似类型的“服务”能够捕获和保存我发送的信息,无论应用程序是否在前台(活动),背景(仍在内存中)或未激活(不在内存中)。因此,我必须使用通知消息而不是像我为 Android 设计的数据消息。
经过大量阅读以了解 Apple APNS 以及 iOS 应用程序和 APNS 服务器之间的 Firebase 接口,查看了关于 stackoverflow 和其他网络资源的无数帖子,我终于弄清楚了如何让它满足我的要求。
当从服务器(或 Firebase 控制台,因为 FCM 默认为 Notification NOT Data 消息)发送 Firebase 云消息传递 (FCM) 通知消息时,它会通过 APNS 传递并在 iOS 设备上作为通知呈现。当用户点击通知横幅时,iOS 会执行以下操作:如果应用程序未运行/加载 iOS 启动应用程序,如果应用程序已加载/运行但在后台 iOS 将应用程序带到前台或者如果应用程序是在前台(所有三种情况),然后通过 func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {} 传递消息内容。
可以肯定的是,您必须启用后台模式并检查远程通知,您不必在有效负载中包含 {"content-available" : 1}。
1) 完成 APNS 和 Firebase 设置,非常简单,生成和注册证书等。
2)在appDelegate,didFinishLaunchingWithOptions中,添加:
Messaging.messaging().delegate = self as? MessagingDelegate
if #available(iOS 10.0, *) {
UNUserNotificationCenter.current().delegate = self
let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
UNUserNotificationCenter.current().requestAuthorization(
options: authOptions,
completionHandler: {_, _ in })
}
else {
let settings: UIUserNotificationSettings =
UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
application.registerUserNotificationSettings(settings)
}
application.registerForRemoteNotifications()
3) 然后将这些回调函数添加到appDelegate:
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
// Print message ID.
if let messageID = userInfo["gcm.message_id"] {
print("\n*** application - didReceiveRemoteNotification - fetchCompletionHandler - Message ID: \(messageID)")
}
// Print full message.
print("\n*** application - didReceiveRemoteNotification - full message - fetchCompletionHandler, userInfo: \(userInfo)")
myNotificationService?.processMessage(title: userInfo["Title"] as! String
, text: userInfo["Text"] as! String, completion: { (success) in
if success {
completionHandler(.newData)
}
else {
completionHandler(.noData)
}
})
}
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler([.alert, .badge, .sound])
}
很有帮助:
https://developer.apple.com/library/archive/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/CreatingtheNotificationPayload.html
https://firebase.googleblog.com/2017/01/debugging-firebase-cloud-messaging-on.html