【发布时间】:2017-03-05 04:11:36
【问题描述】:
我已经让FCM 工作,但我无法让传统的横幅通知工作。
这是我的 AppDelegate.swift 文件中的内容:
import UIKit
import Firebase
import UserNotifications
@UIApplicationMain
final class AppDelegate: UIResponder {
var window: UIWindow?
override init() {
super.init()
FIRApp.configure()
}
}
// MARK: - UIApplicationDelegate
extension AppDelegate: UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool {
let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
UNUserNotificationCenter.current().requestAuthorization(options: authOptions, completionHandler: { _, _ in })
UNUserNotificationCenter.current().delegate = self
FIRMessaging.messaging().remoteMessageDelegate = self
application.registerForRemoteNotifications()
NotificationCenter.default.addObserver(self, selector: #selector(tokenRefreshNotification), name: .firInstanceIDTokenRefresh, object: nil)
return true
}
func tokenRefreshNotification(notification: Notification) {
if let refreshedToken = FIRInstanceID.instanceID().token() {
print("InstanceID token: \(refreshedToken)")
}
connectToFcm()
}
func connectToFcm() {
FIRMessaging.messaging().connect { error in
if error != nil {
print("Unable to connect with FCM. \(error)")
} else {
print("Connected to FCM.")
}
}
}
func applicationDidBecomeActive(_ application: UIApplication) {
connectToFcm()
}
}
// MARK: - UNUserNotificationCenterDelegate
extension AppDelegate: UNUserNotificationCenterDelegate {
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
let userInfo = notification.request.content.userInfo
print("Message ID: \(userInfo["gcm.message_id"]!)")
print(userInfo)
completionHandler([.alert, .sound])
}
}
// MARK:
extension AppDelegate: FIRMessagingDelegate {
func applicationReceivedRemoteMessage(_ remoteMessage: FIRMessagingRemoteMessage) {
print("FIRMessagingRemoteMessage Received: \(remoteMessage.appData)")
}
}
一切都按照documentation进行配置。当我通过 Firebase 上的通知控制台向我的应用发送消息时,我得到了控制台输出。
但是,发送通知时不会出现横幅。当应用程序处于后台时,似乎也不会发送通知 - 仅当应用程序处于前台时。
寻求帮助。提前致谢!
【问题讨论】:
-
令牌生成成功了吗?
-
@NaveenRamanathan 我刚刚创建了一个新属性 -
let token = FIRInstanceID.instanceID().token()!并且崩溃了。我猜它没有成功生成。虽然文档从未提及令牌... -
token会在调用tokenRefreshNotification后生成。如果您在生成令牌之前尝试获取令牌,您的应用程序将会崩溃。是否调用了 tokenRefreshNotification 方法并且 print("InstanceID token: (refreshedToken)") 打印了令牌?
-
它没有打印令牌。
-
您正在测试的设备的 iOS 版本是什么
标签: ios swift firebase apple-push-notifications firebase-cloud-messaging