iOS FCM通知在后台无法工作

4
我正在使用Swift开发一个应用程序,需要使用FCM作为通知服务。在我的应用程序中,只有在前台而不是后台时,FCM才能正常工作。
我已经尝试了几种方法,例如:
- 禁用和启用方法交换(swizzling); - 将优先级设置为高; - 在有效负载中将数据更改为通知;
我还遇到了一个错误:
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
你的意思是应用程序在后台运行时不起作用还是在被杀死状态下不起作用? - Shubhank
@Shubhank,是的,当在后台时它不起作用。 - Dirus
你尝试过在 content_available 中包含值为 true 吗? - AL.
另外,您确定已经上传了必要的证书吗? - AL.
显示剩余2条评论
2个回答

0
尝试按照@AL的建议添加值为true的content_avaliable和一个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上行为仍然存在。


0

我在iOS\Swift方面还是比较新手...但我认为也许这段代码可以:

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

每次应用程序进入后台时,它会使您退出 Firebase 云消息传递...这就是为什么您无法收到通知的原因。

您可以尝试将此方法注释掉,看看是否有效?

请告诉我,谢谢。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接