didReceiveRemoteNotification不工作斯威夫特(didReceiveRemo

2019-09-30 10:33发布

import UIKit
import Firebase
import FirebaseInstanceID
import FirebaseMessaging

class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

        FIRApp.configure()

        let settings: UIUserNotificationSettings =
            UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil)
        application.registerUserNotificationSettings(settings)
        application.registerForRemoteNotifications()

        // Add observer for InstanceID token refresh callback.
        NSNotificationCenter
            .defaultCenter()
            .addObserver(self, selector: #selector(AppDelegate.tokenRefreshNotificaiton),
                         name: kFIRInstanceIDTokenRefreshNotification, object: nil)

        return true
    }

    func applicationDidEnterBackground(application: UIApplication) {


        FIRMessaging.messaging().disconnect()
        print("Disconnected from FCM.")
    }

    func applicationWillEnterForeground(application: UIApplication) {
        // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
    }

    func applicationDidBecomeActive(application: UIApplication) {
        connectToFcm()
        // 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.
    }

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

    func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject],
                     fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {

        FIRMessaging.messaging().appDidReceiveMessage(userInfo)
        print("Message ID: \(userInfo["gcm.message_id"]!)")

        // Print full message.
        print("%@", userInfo)
    }


    func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) {
        print(error)
    }
    func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {

        FIRInstanceID.instanceID().setAPNSToken(deviceToken, type: FIRInstanceIDAPNSTokenType.Sandbox)
    }


    func tokenRefreshNotificaiton(notification: NSNotification) {
        guard let refreshedToken = FIRInstanceID.instanceID().token()
            else {
                return
        }
        //refreshedToken = FIRInstanceID.instanceID().token()!
        print("InstanceID token: \(refreshedToken)")

        utill.tokenDefault.setValue(refreshedToken, forKey: "tokenId")
        // Connect to FCM since connection may have failed when attempted before having a token.
        connectToFcm()
    }


    func connectToFcm() {
        FIRMessaging.messaging().connectWithCompletion { (error) in
            if (error != nil) {
                print("Unable to connect with FCM. \(error)")
            } else {
                print("Connected to FCM.")
            }
        }
    } 
}

https://firebase.google.com/docs/notifications/ios/console-device

一切工作正常发送推送通知给其他设备,甚至未来,如果我们直接从发送弹出消息通知Firebase帐户。 但didReceiveRemoteNotification同时接到通知是没有得到调用。

Answer 1:

尝试这个:

func userNotificationCenter(_ center: UNUserNotificationCenter,  willPresent notification: UNNotification, withCompletionHandler   completionHandler: @escaping (_ options:   UNNotificationPresentationOptions) -> Void) {
    print("Handle push from foreground")
    // custom code to handle push while app is in the foreground
    print("\(notification.request.content.userInfo)")
 }

func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
    print("Handle push from background or closed")
    // if you set a member variable in didReceiveRemoteNotification, you  will know if this is from closed or background
    print("\(response.notification.request.content.userInfo)")
}

在此之前,你必须在应用程序中添加了两个通知框架这个代码添加到您的应用程序的代表。

1.UserNotificationUI.framework 2.UserNotification.framework



文章来源: didReceiveRemoteNotification not working Swift