在配置我的 iOS 应用程序以通过 Firebase Cloud Messaging 接收推送通知时,我一直在尝试让服务器发送的推送通知正常工作。但是,当我使用 FCM 控制台进行测试时,测试通知会到达 iPhone 中。
我在 AppDelegate 中尝试了很多不同的配置,包括打开和关闭 swizzling。
有人知道我可能会错过什么吗?
原来需要在消息的APNS字段中发送专门针对APNS的通知内容。通过阅读此主题发现。
总之,你应该添加几个方法。另外,您可以使用
https://icloud.developer.apple.com/dashboard/notifications
进行测试,为此您需要第 2 点中的 deviceToken
。此外,您的服务器应该添加参数 sound: default
和 mutable-content: 1
。
1.
func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String?) {
let dataDict: [String: String] = ["token": fcmToken ?? ""]
NotificationCenter.default.post(
name: Notification.Name("FCMToken"),
object: nil,
userInfo: dataDict
)
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
let deviceTokenString = deviceToken.reduce("", { $0 + String(format: "%02X", $1) })
Messaging.messaging().apnsToken = deviceToken
}
Messaging.messaging().token { [weak self] token, error in
if let error = error {
print("Error fetching FCM registration token: \(error)")
} else if let token = token {
print("FCM registration token: \(token)")
self?.registerFCMToken(token: token) // send your FCM token to server
}
}
func userNotificationCenter(_ center: UNUserNotificationCenter,
willPresent notification: UNNotification) async
-> UNNotificationPresentationOptions {
return [[.sound, .badge, .banner]]
}