没有收到来自 Firebase 控制台的推送通知
Posted
技术标签:
【中文标题】没有收到来自 Firebase 控制台的推送通知【英文标题】:not geting push notification from firebase console 【发布时间】:2019-09-17 08:03:57 【问题描述】:我已经实现了有关实现推送通知的所有步骤,但是当我测试通知时,控制台它不会出现在 iPhone 上,但是当我使用来自“https://pushtry.com/”的密码 n 令牌的生产 apns 证书 n 进行测试时,它工作正常。我无法纠正为什么会这样。我还启用了功能部分的推送通知。谢谢 下面是我的应用委托代码
mport Firebase
import FirebaseMessaging
import FirebaseInstanceID
import UserNotifications
@UIApplicationMain
class AppDelegate: UIResponder,UIApplicationDelegate,MessagingDelegate,UNUserNotificationCenterDelegate
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool
// Override point for customization after application launch.
GMSServices.provideAPIKey("AIzaSyB5HWsalLBmBFjLC3NjTUF2KB7i5zvz45k")
GMSPlacesClient.provideAPIKey("AIzaSyB5HWsalLBmBFjLC3NjTUF2KB7i5zvz45k")
let notificationCenter = UNUserNotificationCenter.current()
// It is For Notification Allow Authentications
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) (isGranted, err) in
guard isGranted else return
self.getNotificationSettings()
if err != nil
//Something bad happend
print("Erroo ocured......")
else
print(" Success.........All good")
UNUserNotificationCenter.current().delegate = self
Messaging.messaging().delegate = self // it is very important to Generate Firebase registration token, otherwise "didReceiveRegistrationToken" method will not called.
DispatchQueue.main.async
UIApplication.shared.registerForRemoteNotifications()
FirebaseApp.configure()
return true
func getNotificationSettings()
UNUserNotificationCenter.current().getNotificationSettings (settings) in
print("Notification settings: \(settings)")
guard settings.authorizationStatus == .authorized else return
DispatchQueue.main.async(execute: UIApplication.shared.registerForRemoteNotifications() )
func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String)
print("Firebase registration token::::::: \(fcmToken)")
UserDefaults.standard.set(fcmToken, forKey: "deviceToken")
func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage)
print("Received data message: \(remoteMessage.appData)")
func messaging(_ messaging: Messaging, didRefreshRegistrationToken fcmToken: String)
NSLog("[RemoteNotification] didRefreshRegistrationToken: \(fcmToken)")
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error)
// Print the error to console (you should alert the user that registration failed)
print("APNs registration failed: \(error)")
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void)
//NSLog("[RemoteNotification] applicationState: \(applicationStateString) didReceiveRemoteNotification for ios9: \(userInfo)")
if UIApplication.shared.applicationState == .active
//TODO: Handle foreground notification
else
//TODO: Handle background notification
// Print full message.
print(userInfo)
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void)
// show the notification alert (banner), and with sound
completionHandler([.alert, .sound])
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void)
// tell the app that we have finished processing the user’s action / response
let application = UIApplication.shared
if(application.applicationState == .active)
print("user tapped the notification bar when the app is in foreground")
if(application.applicationState == .inactive)
print("user tapped the notification bar when the app is in background")
completionHandler()
func applicationWillResignActive(_ application: UIApplication)
func applicationDidEnterBackground(_ application: UIApplication)
func applicationWillEnterForeground(_ application: UIApplication)
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
func applicationWillTerminate(_ application: UIApplication)
self.saveContext()
【问题讨论】:
【参考方案1】:需要执行几个步骤来测试推送通知:
确保使用真实设备进行测试 您可以在函数 didRegisterForRemoteNotificationsWithDeviceToken 中获取远程实例 ID,如下所示,然后使用 Firebase 控制台将推送通知直接发送到设备令牌:func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) InstanceID.instanceID().instanceID (result, error) in if let error = error print("Error fetching remote instange ID: \(error)") else if let result = result print("Remote instance ID token: \(result.token)")
来源:https://firebase.google.com/docs/cloud-messaging/ios/client
如果不起作用,请检查您是否在 Firebase 控制台设置中上传了正确的 APNs 身份验证密钥或 APNs 证书。【讨论】:
【参考方案2】:**首先您应该检查所有证书类型的东西是否正确** 之后在 appdelegate 中
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool
// START register for notifications
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 )
else
let settings: UIUserNotificationSettings =
UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
application.registerUserNotificationSettings(settings)
application.registerForRemoteNotifications()
// END register for notifications
func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String)
InstanceID.instanceID().instanceID (result, error) in
if let error = error
print("Error fetching remote instance ID: \(error)")
else if let result = result
print("Result \(result)")
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data)
let deviceTokenString = deviceToken.hexString
还将您的 p.12 文件上传到 firebase 控制台
【讨论】:
我已经完成了所有的步骤 n 并且我已经将 .p12 文件上传到了 firebase 控制台,仍然无法收到通知以上是关于没有收到来自 Firebase 控制台的推送通知的主要内容,如果未能解决你的问题,请参考以下文章