Firebase-推送通知-不能按预期工作

时间:2018-11-29 03:14:45

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

为了尝试使用Firebase推送通知,我一直关注以下三个文档: OneTwoThreeFour

我有一个问题,但是在问之前;这是我可以看到的:

当我的应用程序位于前台并发送通知时,只会调用此函数:

userNotificationCenter(_:willPresent:withCompletionHandler:)

如果我点击通知,那么该通知也称为:

userNotificationCenter(_:didReceive:withCompletionHandler:)

当我的应用程序在后台并发送通知时,什么也没叫。

如果我点击通知,则该通知称为:

userNotificationCenter(_:didReceive:withCompletionHandler:)

由于这种情况,无需做出任何反应(通过点击通知);我可以使用 userNotificationCenter(_:willPresent:withCompletionHandler:)函数让应用程序在前台到达通知时执行一些有用的操作。

另一方面,在后台,如果用户点击通知,我只能让该应用在通知到达时执行一些有用的操作。

即使用户没有反应,我是否也可以让应用执行一些有用的操作?

这是我目前拥有的相关代码:

import UIKit
import Firebase
import UserNotifications
import FirebaseInstanceID
import FirebaseMessaging


@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate, MessagingDelegate {
    var window: UIWindow?

    func application(_ application: UIApplication, 
                     didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        window = UIWindow(frame: UIScreen.main.bounds)

        UNUserNotificationCenter.current().delegate = self
        let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
        UNUserNotificationCenter.current().requestAuthorization(
            options: authOptions,
            completionHandler: {
                granted, error in
                if error != nil {print("Error: \(error!)")}

                if granted {
                    DispatchQueue.main.async
                        {application.registerForRemoteNotifications()}
                }
        })

        FirebaseApp.configure()
        .......

        return true
    }


    func application(_ application: UIApplication,
                     didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
        print(#function)
        if let messageID = userInfo[gcmMessageIDKey] {
            print("Message ID: \(messageID)")
        }

        // Print full message.
        print(userInfo)
    }


    func application(_ application: UIApplication,
                     didReceiveRemoteNotification userInfo: [AnyHashable: Any],
                     fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
        print(#function)
        if let messageID = userInfo[gcmMessageIDKey] {
            print("Message ID: \(messageID)")
        }

        // Print full message.
        print(userInfo)

        completionHandler(UIBackgroundFetchResult.newData)
    }
}

有关信息,我正在使用Xcode版本10.1,iOS 12.1和Swift 4.2。

1 个答案:

答案 0 :(得分:0)

swift 4.2,Xcode 10.0,IOS 12.0

import UIKit
import Firebase
import UserNotifications
import FirebaseInstanceID
import FirebaseMessaging

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate, MessagingDelegate {
    var window: UIWindow?

    func application(_ application: UIApplication,
                     didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        window = UIWindow(frame: UIScreen.main.bounds)

        if #available(iOS 10.0, *) {
            let center = UNUserNotificationCenter.current()
            center.requestAuthorization(options: [.badge, .alert , .sound]) { (granted, error) in
                let type: UIUserNotificationType = [UIUserNotificationType.badge, UIUserNotificationType.alert, UIUserNotificationType.sound]
                let setting = UIUserNotificationSettings(types: type, categories: nil)
                UIApplication.shared.registerUserNotificationSettings(setting)
                UIApplication.shared.registerForRemoteNotifications()
            }
        } else {
            let type: UIUserNotificationType = [UIUserNotificationType.badge, UIUserNotificationType.alert, UIUserNotificationType.sound]
            let setting = UIUserNotificationSettings(types: type, categories: nil)
            UIApplication.shared.registerUserNotificationSettings(setting)
            UIApplication.shared.registerForRemoteNotifications()
        }

        application.registerForRemoteNotifications()

        if(FIRApp.defaultApp() == nil){
            FIRApp.configure()
        }
        NotificationCenter.default.addObserver(self,
                                               selector: #selector(self.tokenRefreshNotification(notification:)),
                                               name: NSNotification.Name.firInstanceIDTokenRefresh,
                                               object: nil)

        return true
    }


    @available(iOS 10.0, *)
    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        let userInfo = response.notification.request.content.userInfo as? NSDictionary
        _ = UIStoryboard(name: "Main", bundle: nil)
        let appdelegate = UIApplication.shared.delegate as! AppDelegate
        let aps = userInfo?["aps"] as! NSDictionary
    }

    @available(iOS 10.0, *)
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        completionHandler([.alert, .badge, .sound])
    }
}

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    // Convert token to string

    let deviceTokenString = deviceToken.reduce("", {$0 + String(format: "%02X", $1)})
    print("Device Token", deviceTokenString)
    FIRInstanceID.instanceID().setAPNSToken(deviceToken, type: FIRInstanceIDAPNSTokenType.unknown)
}

func application(_ application: UIApplication, didReceiveRemoteNotification data: [AnyHashable : Any]) {
    let appdelegate = UIApplication.shared.delegate as! AppDelegate
    let aps = data["aps"] as! NSDictionary
    let state = UIApplication.shared.applicationState
    if state == .background {
    }
    if state == .active {
    }
}

//MARK: Notification Center Call
func callNotificationCenter(){
    NotificationCenter.default.post(name: NSNotification.Name(rawValue: "reloadData"), object: nil)
}

func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
}

// start firebase
@objc func tokenRefreshNotification(notification: NSNotification) {
    let refreshedToken = FIRInstanceID.instanceID().token()
    print(refreshedToken)
    connectToFcm()
}

func connectToFcm() {
    FIRMessaging.messaging().connect { (error) in
        if (error != nil) {
            print("Unable to connect with FCM. \(error?.localizedDescription ?? "")")

        } else {
            print("Connected to FCM")
        }
    }
}