我正在创建一个iOS项目,将使用Firebase Cloud Messaging (FCM) 通过Firebase/APNS通知向iOS设备发送自定义数据元素,从公司服务器传递。首先,我必须理解的是,与Android不同,iOS没有类似的“服务”,能够捕获和保存我发送的信息,无论应用程序是在前台(活动状态),后台(仍在内存中)还是非活动状态(不在内存中)。因此,我必须使用通知消息而不是像我为Android设计的数据消息。经过大量阅读,了解Apple APNS和iOS应用程序与APNS服务器之间的Firebase接口,在stackoverflow和其他网络资源上查看无数帖子后,我终于弄清楚如何满足我的要求。
当服务器(或Firebase控制台,因为FCM默认为通知而不是数据消息)发送Firebase云消息(FCM)通知消息时,它通过APNS传递并在iOS设备上显示为通知。当用户点击通知横幅时,iOS会执行以下操作:如果应用程序未运行/加载,则iOS启动应用程序;如果应用程序已加载/运行但在后台,则iOS将应用程序带到前台;或者如果应用程序在前台(这三种情况),则消息内容随后通过函数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) {
if let messageID = userInfo["gcm.message_id"] {
print("\n*** application - didReceiveRemoteNotification - fetchCompletionHandler - Message ID: \(messageID)")
}
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