【发布时间】: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