FirebasePush通知仅显示在控制台中,不会在后台加载

时间:2016-12-23 11:37:26

标签: ios swift firebase push-notification firebase-cloud-messaging

我准备了所有证书,将它们上传到Firebase控制台,更新了我的App ID以及我的Xcode项目中的设置。但是我的应用无法显示任何推送通知。如果我从Firebase控制台发送推送通知,则只能在运行我的应用程序时在控制台中看到该消息,而不是在后台模式下。我使用的是真正的设备/ iPhone 6S。

此外,如果我从AppDelegate评论所有断开连接部分,控制台会显示以下错误。

Unable to connect with FCM. Optional(Error Domain=com.google.fcm Code=2001 "(null)") 

我在AppDelegate.swift中准备了Firebase推送通知:

import UIKit
import UserNotifications

import Firebase
import FirebaseAuth
import FirebaseMessaging
import FirebaseDatabase
import FirebaseInstanceID
import FirebaseRemoteConfig

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?


    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        application.statusBarStyle = .lightContent
        FIRApp.configure()
        FIRDatabase.database().persistenceEnabled = true

        //let _ = RemoteConfigValues.sharedInstance

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

        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.tokenRefreshNotification), name: kFIRInstanceIDTokenRefreshNotification, object: nil)
        logUser()

        return true
    }

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

        FIRInstanceID.instanceID().setAPNSToken(deviceToken, type: FIRInstanceIDAPNSTokenType.Unknown)

        print("tokenString: \(tokenString)")
    }

    // [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

        // 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) {
        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]

    func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) {
        print(error.localizedDescription)
    }

    // [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) {
        application.applicationIconBadgeNumber = 0
        connectToFcm()
    }

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


}

1 个答案:

答案 0 :(得分:0)

即使我遇到了这个错误,当我更改了发送到以下内容的通知数据时,它对我有用

{“to”:“coYbqscbjkA,S”,“priority”:“high”  “通知”:{“正文”:“12345”,“service_type”:“我的服务”}}

检查一次......希望它有效......!