【问题标题】:Firebase notificationFirebase 通知
【发布时间】:2016-06-29 12:41:26
【问题描述】:

在我的应用程序中,我使用 Firebase 接收通知,但我遇到了一个问题:当我从 Firebase 控制台发送通知时,我只听到通知的振动,并且可以在日志中看到消息正文。我无法将消息正文显示为文本和图标的横幅通知。

我遵循here 的官方指南,但它不起作用。

这是我的 AppDelegate:

import UIKit
import Firebase
import FirebaseInstanceID
import FirebaseMessaging

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

var window: UIWindow?


func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

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

    FIRApp.configure()

    // Add observer for InstanceID token refresh callback.
    NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.tokenRefreshNotification),
                                                     name: kFIRInstanceIDTokenRefreshNotification, object: nil)
    return true
}


func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject],
                 fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {

    // TODO: Handle data of notification
    print("This is userInfo -> \(userInfo)")

    print("")
    print(userInfo["notification"]!["body"])
    print("")

    FIRMessaging.messaging().appDidReceiveMessage(userInfo)
    completionHandler(.NoData)


    NSLog("startLocalNotification")
    var notification: UILocalNotification = UILocalNotification()
    notification.fireDate = NSDate(timeIntervalSinceNow: 7)
    notification.alertBody =  userInfo["body"] as? String
    notification.timeZone = NSTimeZone.defaultTimeZone()
    notification.soundName = UILocalNotificationDefaultSoundName
    notification.applicationIconBadgeNumber = 5
    notification.alertAction = "open"
    UIApplication.sharedApplication().scheduleLocalNotification(notification)

}

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

// [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 applicationWillResignActive(application: UIApplication) {

}

func applicationDidEnterBackground(application: UIApplication) {
    //Uncomment below to disconnect
    //FIRMessaging.messaging().disconnect()
    //print("Disconnected from FCM.")
}

func applicationWillEnterForeground(application: UIApplication) {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

func applicationDidBecomeActive(application: UIApplication) {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    connectToFcm()
}
}

这是我的视图控制器:

import UIKit
import Firebase
import FirebaseInstanceID
import FirebaseMessaging

class ViewController: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}


@IBAction func handleLogTokenTouch(sender: UIButton) {
    let token = FIRInstanceID.instanceID().token()
    //        print("InstanceID token: \(token!)")
    print("InstanceID token: \(token)")

}

@IBAction func handleSubscribeTouch(sender: UIButton) {
    // [START subscribe_topic]
    FIRMessaging.messaging().subscribeToTopic("/topics/news")
    print("Subscribed to news topic")
    // [END subscribe_topic]
} 
}

如何在横幅中显示通知?

提前致谢。

【问题讨论】:

  • 如果您的应用程序正在运行或在前台,应用程序只会调用委托方法,不会显示任何警报或横幅。如果您的应用程序在后台或被终止(不在前台),将显示警报或横幅。要在应用程序运行时显示横幅,您需要为其编写自己的代码。参考this post
  • @DipenPanchasara 如果我杀死我的应用程序然后我从控制台发送通知,我的设备上什么也没有出现
  • Alert 或 Banner 由操作系统自己处理,如果你想显示它注释掉你的 UILocalNotification 它将不起作用。当您的应用程序未运行时,系统将自动处理通知并显示适当的警报或横幅。我相信您了解上下文。
  • 在 Apple 文档的UIApplicationDelegate section 中了解更多信息。
  • @DipenPanchasara 我延迟了 UILocalNotification,但它仅在我重新打开应用程序并显示包含数据的日志时才会振动。

标签: ios swift firebase uilocalnotification firebase-cloud-messaging


【解决方案1】:

您需要按照应用程序的状态处理通知,如下所示, 1. 背景:应用程序将根据用户设置的通知显示通知。 (横幅、警报等) 2. 前台:当应用程序在前台时,应用程序不会显示任何通知。

如果您希望即使应用在前台也能通知用户,您需要稍微自定义您的代码。 将以下代码添加到您的 didReceivedRemoteNotification 方法中

    func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject],
                     fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {

        // TODO: Handle data of notification
        print("This is userInfo -> \(userInfo)")

        print("")
        print(userInfo["notification"]!["body"])
        print("")
       // I don't what the following two lines of code doing extactly 
        FIRMessaging.messaging().appDidReceiveMessage(userInfo)
        completionHandler(.NoData)
      // My code is as follows
      if application.applicationState == UIApplicationState.Active {
            //show a alert here
       }
    }

【讨论】:

  • 我暂时无法显示横幅
  • 如果您想在用户使用应用程序时在应用程序中显示自定义横幅(应用程序是前台),那么在 git / pod github.com/bryx-inc/BRYXBanner 上可以使用 3rd 方横幅@
【解决方案2】:
you have to implement the message handling 

[开始 ios_10_message_handling]

  @available(iOS 10, *)
    extension AppDelegate : UNUserNotificationCenterDelegate {

    // Receive displayed notifications for iOS 10 devices.
    func userNotificationCenter(_ center: UNUserNotificationCenter,
                                willPresent notification: UNNotification,
                                withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        let userInfo = notification.request.content.userInfo

        // With swizzling disabled you must let Messaging know about the message, for Analytics
        Messaging.messaging().appDidReceiveMessage(userInfo)
        // Print message ID.
        if let messageID = userInfo[gcmMessageIDKey] {
            print("Message ID: \(messageID)")
        }
        print(userInfo)

        // Change this to your preferred presentation option
     completionHandler([.alert, .badge, .sound]) 

       }

    func userNotificationCenter(_ center: UNUserNotificationCenter,
                                didReceive response: UNNotificationResponse,
                                withCompletionHandler completionHandler: @escaping () -> Void) {
        let userInfo = response.notification.request.content.userInfo
        // Print message ID.
        if let messageID = userInfo[gcmMessageIDKey] {
            print("Message ID: \(messageID)")
        }

        // Print full message.
        print(userInfo)

        completionHandler()

    }
    }
    // [END ios_10_message_handling]
    extension AppDelegate : MessagingDelegate {
    // [START refresh_token]
    func messaging(_ messaging: Messaging, didRefreshRegistrationToken fcmToken: String) {
    print("Firebase registration token: (fcmToken)")
    }

    // Receive data messages on iOS 10+ directly from FCM (bypassing APNs) when the app is in the foreground.
    // To enable direct data messages, you can set Messaging.messaging().shouldEstablishDirectChannel to true.
    func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) {
    print("Received data message: (remoteMessage.appData)")
    }
    }

参考: https://github.com/firebase/quickstart-ios/issues/286#issuecomment-304978967

希望对你有帮助

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-04
    • 2017-03-05
    • 2018-02-21
    • 2018-09-19
    • 2020-05-26
    • 1970-01-01
    相关资源
    最近更新 更多