简体   繁体   English

Firebase-推送通知-不起作用

[英]Firebase - Push Notifications - Not working

I am just trying out Push Notifications with Firebase; 我只是在尝试使用Firebase推送通知; as a start I followed this document: https://www.appcoda.com/firebase-push-notifications/ 首先,我遵循以下文档: https : //www.appcoda.com/firebase-push-notifications/

Here is the relevant code I have at this point: (It builds without any problem) 这是我目前拥有的相关代码:(它的构建没有任何问题)

......

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    ......
    UNUserNotificationCenter.current().delegate = self
    let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
    UNUserNotificationCenter.current().requestAuthorization(
        options: authOptions,
        completionHandler: {_, _ in })
    application.registerForRemoteNotifications()
    FirebaseApp.configure()
    ......

    return true
}

......

// The callback to handle data message received via FCM for devices running iOS 10 or above.
func applicationReceivedRemoteMessage(_ remoteMessage: MessagingRemoteMessage) {
    print(#function)
    print(remoteMessage.appData)
}

When I try to test it (following the advice in the document mentioned earlier), the function applicationReceivedRemoteMessage() never gets called and I don't see anything happening. 当我尝试对其进行测试时(遵循前面提到的文档中的建议),函数applicationReceivedRemoteMessage()永远不会被调用,并且我什么也看不见。 What am I missing? 我想念什么? Is there something I should first look at? 有什么我应该首先看的吗?

For information, I am using Xcode Version 10.1, iOS 12.1 and Swift 4.2. 有关信息,我正在使用Xcode版本10.1,iOS 12.1和Swift 4.2。

Check this code below: 检查以下代码:

import Firebase
import UserNotifications

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate, MessagingDelegate {

var window: UIWindow?

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
     setupFireBase(application)
}

func setupFireBase(_ application: UIApplication) {
    FirebaseApp.configure()
    Messaging.messaging().delegate = self

    if #available(iOS 10.0, *) {
        // For iOS 10 display notification (sent via APNS)
        UNUserNotificationCenter.current().delegate = self
        let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
        UNUserNotificationCenter.current().requestAuthorization(
            options: authOptions,
            completionHandler: {_, _ in })
    } else {
        let settings: UIUserNotificationSettings =
            UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
        application.registerUserNotificationSettings(settings)
    }
    application.registerForRemoteNotifications()
}

func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
    print("Firebase registration token: \(fcmToken)")
    print(messaging)
    ClassUserDefault.shared.deviceToken = fcmToken
    let dataDict: [String: String] = ["token": fcmToken]
    NotificationCenter.default.post(name: Notification.Name("FCMToken"), object: nil, userInfo: dataDict)
    // TODO: If necessary send token to application server.
    // Note: This callback is fired at each app startup and whenever a new token is generated.
    connectToFcm()
}

// [START refresh_token]
func tokenRefreshNotification(_ notification: Notification) {
    InstanceID.instanceID().instanceID { (result, error) in
        if let error = error {
            print("Error fetching remote instange ID: \(error)")
        } else if let result = result {
            print("Remote instance ID token: \(result.token)")
        }
    }
    connectToFcm()
}

func connectToFcm() {
    InstanceID.instanceID().instanceID { (result, error) in
        if let _ = error {
            return
        } else if let result = result {
            print("Remote instance ID token: \(result.token)")
        }
    }
}

func application(application: UIApplication,
                 didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
    Messaging.messaging().apnsToken = deviceToken as Data
}

public func application(received remoteMessage: MessagingRemoteMessage) {
    print(remoteMessage.appData)
}

@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler   completionHandler: @escaping (_ options: UNNotificationPresentationOptions) -> Void) {
    completionHandler([UNNotificationPresentationOptions.alert, UNNotificationPresentationOptions.sound, UNNotificationPresentationOptions.badge])
    print("Handle push from background or closed")
    print("\(notification.request.content.userInfo)")
    let _ResponsePush = ClassResponsePush(fromData: notification.request.content.userInfo)
    //AudioServicesPlaySystemSound(kSystemSoundID_Vibrate)

    if notification.request.content.userInfo.isEmpty {
        return
    } else {
    }
    print(_ResponsePush)
}

@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
    print("Handle push from background or closed")
    print("\(response.notification.request.content.userInfo)")
    let _ResponsePush = ClassResponsePush(fromData: response.notification.request.content.userInfo)
    if response.notification.request.content.userInfo.isEmpty { return } else {
        handlePush(userInfo: _ResponsePush)
    }
    print(_ResponsePush)
}

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    let chars = (deviceToken as NSData).bytes.bindMemory(to: CChar.self, capacity: deviceToken.count)
    var token = ""
    for i in 0..<deviceToken.count {
        token += String(format: "%02.2hhx", arguments: [chars[i]])
    }
    print("Device Token = ", token)
}

func applicationReceivedRemoteMessage(_ remoteMessage: MessagingRemoteMessage) {
    print("Received data message: \(remoteMessage.appData)")
}

func handlePush(userInfo: ClassResponsePush) {

}
}

Don't forget to add .p12 file in cloud messaging of project settings in firebase console. 不要忘记在Firebase控制台的项目设置的云消息传递中添加.p12文件。

Hope it helps :) 希望能帮助到你 :)

hello Michel, 你好,米歇尔,

Based on your reference link seem like you miss this line 根据您的参考链接,您好像错过了这一行

 FIRMessaging.messaging().remoteMessageDelegate = self 
   if #available(iOS 10.0, *) {
        // For iOS 10 display notification (sent via APNS)
        UNUserNotificationCenter.current().delegate = self
        let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
        UNUserNotificationCenter.current().requestAuthorization(
        options: authOptions,
        completionHandler: {_, _ in })
        // For iOS 10 data message (sent via FCM
        FIRMessaging.messaging().remoteMessageDelegate = self
    } else {
        let settings: UIUserNotificationSettings =
        UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
          application.registerUserNotificationSettings(settings)
    }

    application.registerForRemoteNotifications()

    FIRApp.configure()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM