didReceiveRemoteNotification not working Swift

风流意气都作罢 提交于 2019-12-24 08:18:50

问题


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

Everything works fine with sending push notification to other device and even popup notification coming if we send message directly from Firebase account. But didReceiveRemoteNotification is not getting called while receiving notification.


回答1:


Try this:

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)")
}

Add this code to your app delegates before that you have to add two notification framework in your application.

1.UserNotificationUI.framework 2.UserNotification.framework



来源:https://stackoverflow.com/questions/40280986/didreceiveremotenotification-not-working-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!