ios - Firebase - 推送通知 - 没有按预期工作

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

为了尝试使用 Firebase 推送通知,我一直在遵循以下三个文档: One , Two , ThreeFour .

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

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

userNotificationCenter(_:willPresent:withCompletionHandler:)

如果我点击通知,那么这个通知也被称为:

userNotificationCenter(_:didReceive:withCompletionHandler:)

当我的应用程序在后台运行并发送通知时,不会调用任何内容。

如果我点击通知,则会调用此通知:

userNotificationCenter(_:didReceive:withCompletionHandler:)

由于这种情况,无需使用react(通过点击通知);当通知到达前台时,我可以使用 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。

最佳答案

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

关于ios - Firebase - 推送通知 - 没有按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53531312/

相关文章:

javascript - Firebase update() 不是带有查询的函数

ios - JSON 对象映射 - RestKit

swift - UIPickerView Swift 5 的语法问题

ios - 导航 Controller 无法正常工作

node.js - 根据 Firebase-Admin 中的(prod、dev、test、stag)等环境初始化单独的应用程序

ios - 在加载数据之前完成所有异步请求?

ios - UILabel - 收缩文本而不是截尾

ios - Link error/Build/Products/Debug-找不到iphonesimulator文件

ios - 用彼此不同的随机数填充数组?

ios - 我的 segue 退得太远了