ios - 未调用 FCM didReceiveRemoteNotification

标签 ios swift firebase firebase-cloud-messaging remote-notifications

我的 firebase ios 应用有问题。我的应用程序没有收到通知,甚至 didReceiveRemoteNotification 也没有被调用。我最近为应用程序制定了 2 个目标。在我创建一个单独的目标之前,通知曾经运行良好。

需要澄清的事情:

  1. 我已经为每个目标分离了 Google-Info.plistInfo.plist 文件。这是经过验证的,因为我可以访问 2 个不同的数据库,甚至可以对其中任何一个执行显式操作。

  2. 我对每个目标都有单独的配置文件,APNS 开发和生产证书也是如此。

  3. 所有目标都分配有 APN 验证 key 。

执行完所有这些后,我将执行以下代码:

AppDelegate.swift

import UIKit
import CoreData
import Firebase
import UserNotifications
import FirebaseInstanceID
import FirebaseMessaging
import IQKeyboardManagerSwift
import Fabric
import Crashlytics

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, MessagingDelegate {

var window: UIWindow?
let gcmMessageIDKey = "gcm.message_id"
var tokenExists = false

override init() {
    super.init()

    #if DEVELOPMENT
        print("Development Mode Started")
        let filePath = Bundle.main.path(forResource: "GoogleServiceDev-Info", ofType: "plist")
        guard let fileopts = FirebaseOptions.init(contentsOfFile: filePath!)
            else { assert(false, "Couldn't load config file") }
        FirebaseApp.configure(options: fileopts)
    #else
        print("Production Mode Started")
       FirebaseApp.configure()
    #endif

}

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

    Messaging.messaging().delegate = self
    IQKeyboardManager.sharedManager().enable = true


    if #available(iOS 10.0, *) {
        // For iOS 10 display notification (sent via APNS)
        UNUserNotificationCenter.current().delegate = self as? UNUserNotificationCenterDelegate

        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()
    Fabric.with([Crashlytics.self])

    return true
}

func messaging(_ messaging: Messaging, didRefreshRegistrationToken fcmToken: String) {
    print("Firebase registration token: \(fcmToken)")
}
func applicationWillResignActive(_ application: UIApplication) {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}

func applicationDidEnterBackground(_ application: UIApplication) {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.

}

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 applicationDidBecomeActive(_ application: UIApplication) {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    application.applicationIconBadgeNumber = 0
    let token = Messaging.messaging().fcmToken

    if token != nil {
        tokenExists = true
        let currUser = Auth.auth().currentUser?.uid
        if currUser != nil {
            let ref = FBDataservice.ds.REF_CURR_USER.child("notificationTokens")
            let val = [token! : tokenExists] as [String : Any]
            ref.setValue(val)
        }

    }

    print("FCM token: \(token ?? "")")

}

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any]) {
    print("ADX: Hey")
    if let messageID = userInfo[gcmMessageIDKey] {
        print("Message ID: \(messageID)")
    }

    print("foreground ------------------------  \(userInfo)")
}

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],
                 fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
    print("ADX: Hey2")

    if let messageID = userInfo[gcmMessageIDKey] {
        print("Message ID: \(messageID)")
    }

    if Auth.auth().canHandleNotification(userInfo) {
        completionHandler(.noData)
   }
    print("foreground ------------------------  \(userInfo)")
    completionHandler(UIBackgroundFetchResult.newData)
}



func applicationWillTerminate(_ application: UIApplication) {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

}


@available(iOS 10, *)
extension AppDelegate : UNUserNotificationCenterDelegate {

// Receive displayed notifications for iOS 10 devices.
func userNotificationCenter(_ center: UNUserNotificationCenter,
                            willPresent notification: UNNotification,
                            withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    let userInfo = notification.request.content.userInfo

    // With swizzling disabled you must let Messaging know about the message, for Analytics
    // Messaging.messaging().appDidReceiveMessage(userInfo)
    // Print message ID.
    if let messageID = userInfo[gcmMessageIDKey] {
        print("Message ID: \(messageID)")
    }

    // Print full message.
    print(userInfo)

    // Change this to your preferred presentation option
    completionHandler([])
}

func userNotificationCenter(_ center: UNUserNotificationCenter,
                            didReceive response: UNNotificationResponse,
                            withCompletionHandler completionHandler: @escaping () -> Void) {
    let userInfo = response.notification.request.content.userInfo
    // Print message ID.
    if let messageID = userInfo[gcmMessageIDKey] {
        print("Message ID: \(messageID)")
    }

    // Print full message.
    print(userInfo)

    completionHandler()
}
}

完成所有这些后,我突然停止接收应用程序的通知。我尝试了控制台和云功能都不起作用。

我在这个论坛上搜索了很多问题,但没有找到答案。

任何解决此问题的帮助将不胜感激。

最佳答案

所以,我终于联系了 firebase 支持,结果我不得不在 didFinishLaunchingWithOptions() 中移动 FirbaseApp.configure()。

关于ios - 未调用 FCM didReceiveRemoteNotification,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47133259/

相关文章:

objective-c - 来自 AudioUnitRender 的错误 -50

ios - 如何使用 Alamofire.request() 将 XML soap 响应保存到文件?

ios - 如何将数据传递给从 UIStoryboard 实例化的 TableView Controller ?

mysql - 如何在 google firebase 上托管我的 laravel 项目

ios - 每个星期二的本地通知重复间隔不起作用..我错过了什么?

ios - 如何使用 Swift 从 UITableViewCell 中的 NIB 调整自定义 UIView 的大小?

ios - 在 View Controller 之间传递对象

ios - 添加 ViewController.swift 并重命名后,它不会将我的 viewController 与那个 swift 类链接起来

android - 关于2019年4月11日后GCM实现Android应用(GCM废除)

android - Firebase异常 : Failed to bounce to type in Android but Model class properties and JSON properties are same