我已遵循外部指南在iOS Swift应用(link)中通过FCM实现推送通知,但通过Firebase控制台进行的测试无法正常工作。我已经测试了将消息作为通用消息发送到特定令牌的情况-在真正的iOS设备上无法正常工作。
我做了以下事情:
请在代码下方找到
用户注册后:
let pushManager = PushNotificationManager(userID: userID)
pushManager.registerForPushNotifications()
班级:
import Firebase
import FirebaseFirestore
import FirebaseMessaging
import UIKit
import UserNotifications
class PushNotificationManager: NSObject, MessagingDelegate, UNUserNotificationCenterDelegate {
let userID: String
init(userID: String) {
self.userID = userID
super.init()
}
func registerForPushNotifications() {
if #available(iOS 10.0, *) {
// For iOS 10 display notification (sent via APNS)
UNUserNotificationCenter.current().delegate = self
let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
UNUserNotificationCenter.current().requestAuthorization(
options: authOptions,
completionHandler: {_, _ in })
// For iOS 10 data message (sent via FCM)
Messaging.messaging().delegate = self
} else {
let settings: UIUserNotificationSettings =
UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
UIApplication.shared.registerUserNotificationSettings(settings)
}
UIApplication.shared.registerForRemoteNotifications()
updateFirestorePushTokenIfNeeded()
}
func updateFirestorePushTokenIfNeeded() {
if let token = Messaging.messaging().fcmToken {
let usersRef = Firestore.firestore().collection("Users").document(userID)
usersRef.setData(["fcmToken": token], merge: true)
}
}
func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) {
print(remoteMessage.appData)
}
func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
updateFirestorePushTokenIfNeeded()
}
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
print(response)
}
}