【问题标题】:iOS FCM notification not working in backgroundiOS FCM 通知在后台不起作用
【发布时间】:2016-09-01 09:06:48
【问题描述】:

我正在用 Swift 开发一个必须使用 FCM 作为通知服务的应用程序。在我的应用中,FCM 仅在其处于前台而非后台时才起作用。

我已经尝试了几种方法,例如:

  • 禁用和启用 swizzling 方法
  • priority 设置为high
  • 在我的有效载荷中将 data 更改为 notification

我也遇到了错误:

Failed to fetch APNS token Error Domain=com.firebase.iid Code=1001 "(null)"

但是通知在前台工作没有任何问题。下面是我的 AppDelegate:

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

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

        FIRApp.configure()

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

        return true
    }

    func registerForPushNotifications(application: UIApplication) {
        let notificationSettings = UIUserNotificationSettings(
            forTypes: [.Badge, .Sound, .Alert], categories: nil)
        application.registerUserNotificationSettings(notificationSettings)
    }

    func application(application: UIApplication, didRegisterUserNotificationSettings notificationSettings: UIUserNotificationSettings) {
        if notificationSettings.types != .None {
            application.registerForRemoteNotifications()
        }
    }

    func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
        let tokenChars = UnsafePointer<CChar>(deviceToken.bytes)
        var tokenString = ""

        for i in 0..<deviceToken.length {
            tokenString += String(format: "%02.2hhx", arguments: [tokenChars[i]])
        }

        //Tricky line
        FIRInstanceID.instanceID().setAPNSToken(deviceToken, type: FIRInstanceIDAPNSTokenType.Unknown)
        print("Device Token:", tokenString)
    }

    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 throttle down OpenGL ES frame rates. Games should use this method to pause the game.
    }

    // [START receive_message]
    func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject],
                     fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
        // If you are receiving a notification message while your app is in the background,
        // this callback will not be fired till the user taps on the notification launching the application.
        // TODO: Handle data of notification

        let alertController = UIAlertController(title: "Notification", message: "A standard alert", preferredStyle: .Alert)

        let OKAction = UIAlertAction(title: "OK", style: .Default) { (action:UIAlertAction!) in

        }
        alertController.addAction(OKAction)

        self.window?.rootViewController?.presentViewController(alertController, animated: true, completion:nil)

        // Print message ID.
//        print("Message ID: \(userInfo["gcm.message_id"]!)")

        // Print full message.
        print("%@", userInfo)
    }
    // [END receive_message]

    // [START refresh_token]
    func tokenRefreshNotification(notification: NSNotification) {
        if let refreshedToken = FIRInstanceID.instanceID().token() {
            print("InstanceID token: \(refreshedToken)")
        }

        // Connect to FCM since connection may have failed when attempted before having a token.
        connectToFcm()
    }
    // [END refresh_token]

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

    func applicationDidBecomeActive(application: UIApplication) {
        connectToFcm()
    }

    // [START disconnect_from_fcm]
    func applicationDidEnterBackground(application: UIApplication) {
        FIRMessaging.messaging().disconnect()
        print("Disconnected from FCM.")
    }
    // [END disconnect_from_fcm]

在我的服务器中,我使用类似这样的东西来推送通知:

method: 'POST',
            uri: 'https://fcm.googleapis.com/fcm/send',
            headers: {
                'Content-Type': 'application/json',
                'Authorization':'key= **THE KEY**'
            },
            body: JSON.stringify({
                "to" : " **USER INSTANCEID TOKEN** ",
                "priority":"high",
                "data" : {
                    "title": "FCM TITLE",
                    "body" : "FROM FCM",
                    "badge": "0",
                    "sound": "default"
                }
            })

我尝试到处搜索,但找不到任何解决方案,而且似乎在 FCM 文档中找不到有关此问题的任何内容。

【问题讨论】:

  • 更改您的有效负载以使用通知键而不是数据,这将使其也可以在后台工作
  • @Shubhank 我忘了提到我已经将 data 更改为 notification 反之亦然,对我没有任何作用
  • 你的意思是当应用程序处于后台或应用程序处于终止状态时它不起作用?
  • @Shubhank ya.. 它在后台不起作用
  • 您是否尝试过将content_availabletrue 值一起包含在内?

标签: ios swift firebase firebase-cloud-messaging


【解决方案1】:

我是 iOS\Swift 的新手……但我想可能是这段代码:

// [START disconnect_from_fcm]
    func applicationDidEnterBackground(application: UIApplication) {
        FIRMessaging.messaging().disconnect()
        print("Disconnected from FCM.")
    }
// [END disconnect_from_fcm]

每次应用程序进入后台时都会将您从 Firebase 云消息中注销...这就是您没有收到通知的原因。

你能不能试着注释掉这个方法,看看它是否有效?

LMK,谢谢。

【讨论】:

    【解决方案2】:

    尝试将带有true 值的content_avaliable 添加为@AL。说并添加一个notification 对象。您可以发送带有两个参数(数据和通知)的通知

    这对我有用。

    {
       "to" : " **USER INSTANCEID TOKEN** ",
       "priority":"high",
       "content_avaliable":true,
       "data" : {
            "title": "FCM TITLE",
            "body" : "FROM FCM",
            "badge": "0",
             "sound": "default"
       },
       "notification" : {
            "title": "FCM TITLE",
            "body" : "FROM FCM"
       }
    }
    

    更新: 仅在我的 iPad 上工作,在 iPhone 上这种行为仍在继续。

    【讨论】:

      猜你喜欢
      • 2016-10-20
      • 1970-01-01
      • 2020-02-11
      • 2016-12-24
      • 1970-01-01
      • 2018-03-05
      • 2018-04-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多