【发布时间】:2017-09-14 04:15:31
【问题描述】:
我正在尝试在我的应用程序中实现 firebase 消息传递,但我只在应用程序处于活动状态时收到通知(我可以在控制台中看到它们,但只有当应用程序处于活动状态时。如果它关闭,它们在应用再次激活之前不会出现)。
我打开了后台通知,并将我的 p12 证书加载到了 firebase 设置中。
这是我的应用委托中的代码:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
Fabric.with([Crashlytics.self])
FirebaseApp.configure()
Messaging.messaging().delegate = self
Messaging.messaging().shouldEstablishDirectChannel = true
if #available(iOS 11.0, *){
print("IOS 11")
UNUserNotificationCenter.current().delegate = self
let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
UNUserNotificationCenter.current().requestAuthorization(
options: authOptions,
completionHandler: {_, _ in })
}else 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()
return true
}
func messaging(_ messaging: Messaging, didRefreshRegistrationToken fcmToken: String) {
print("Firebase registration token: \(fcmToken)")
}
@nonobjc func application(application: UIApplication,
didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
Messaging.messaging().apnsToken = deviceToken as Data
}
func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) {
// Convert to pretty-print JSON
guard let data =
try? JSONSerialization.data(withJSONObject: remoteMessage.appData, options: .prettyPrinted),
let prettyPrinted = String(data: data, encoding: .utf8) else {
return
}
print("Received direct channel message:\n\(prettyPrinted)")
}
func application(received remoteMessage: MessagingRemoteMessage){
print("Received Remote Message")
guard let data =
try? JSONSerialization.data(withJSONObject: remoteMessage.appData, options: .prettyPrinted),
let prettyPrinted = String(data: data, encoding: .utf8) else {
return
}
print("Received direct channel message:\n\(prettyPrinted)")
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
print(userInfo)
}
编辑 1: 这是我在控制台中收到的示例通知
{
"from" : "480981200252",
"notification" : {
"e" : "1",
"body" : "hey"
},
"collapse_key" : "com.amplesftwr.thelifeofcarl"
}
【问题讨论】:
-
只是为了确定,这适用于 iOS 10,但不适用于 11?
-
我不确定它是否适用于 10,我正在使用 11。
-
更新:在 ios 10 上的结果相同
-
您能截取您启用的背景模式的屏幕截图吗?您的应用在前台正确接收,因此您不能在与后台相关的设置中设置正确的内容。
-
同时检查您是否为您的应用/设备“允许”通知
标签: ios swift firebase firebase-cloud-messaging