【问题标题】:I am not able to receive data notification iOS swift 3我无法接收数据通知 iOS swift 3
【发布时间】:2017-05-23 07:54:16
【问题描述】:

我正在关注 firebase 提供的采样器项目。 Firebase Cloud Messaging sammple

我的应用代理是

import UIKit
import Firebase
import FirebaseMessaging
import UserNotifications
import FirebaseInstanceID

//add firebase code app delegate code

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

var window: UIWindow?
let gcmMessageIDKey = "gcm.message_id"


func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.


    // Register for remote notifications. This shows a permission dialog on first run, to
    // show the dialog at a more appropriate time move this registration accordingly.
    // [START register_for_notifications]
    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()

    // [END register_for_notifications]
    FirebaseApp.configure()

    // [START set_messaging_delegate]
    Messaging.messaging().delegate = self
    // [END set_messaging_delegate]

    return true

}

// [START receive_message]
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
    // If you are receiving a notification message while your app is in the background,
    // this callback will not be fired till the user taps on the notification launching the application.
    // TODO: Handle data of notification
    // Print message ID.
    if let messageID = userInfo[gcmMessageIDKey] {
        print("Message ID: \(messageID)")
    }

    // Print full message.
    print(userInfo)
}

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],
                 fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
    // If you are receiving a notification message while your app is in the background,
    // this callback will not be fired till the user taps on the notification launching the application.
    // TODO: Handle data of notification
    // Print message ID.
    if let messageID = userInfo[gcmMessageIDKey] {
        print("Message ID: \(messageID)")
    }

    // Print full message.
    print(userInfo)

    completionHandler(UIBackgroundFetchResult.newData)
}
// [END receive_message]


func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
    print("Unable to register for remote notifications: \(error.localizedDescription)")
}

// This function is added here only for debugging purposes, and can be removed if swizzling is enabled.
// If swizzling is disabled then this function must be implemented so that the APNs token can be paired to
// the InstanceID token.
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    print("APNs token retrieved: \(deviceToken)")

    // With swizzling disabled you must set the APNs token here.
    InstanceID.instanceID().setAPNSToken(deviceToken, type: InstanceIDAPNSTokenType.sandbox)

}


}


        // [START 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
    // Print message ID.
    if let messageID = userInfo[gcmMessageIDKey] {
        print("Message ID: \(messageID)")
    }

    // Print full message.
    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)")

    print(fcmToken)

    resgisterNotificationToken(fcmToken: fcmToken)

}
// [END refresh_token]

func application(received remoteMessage: MessagingRemoteMessage) {

    //get called when sending notification from POSTMAN and when app is open

    print("%@", remoteMessage.appData)

    print("%@", remoteMessage)

}


func resgisterNotificationToken(fcmToken:String){

    //let deviceId = UIDevice.current.identifierForVendor!.uuidString

    //let parameters = ["OTY": AppConstants.init().OS_TYPE,"REGID": fcmToken] as Dictionary<String, String>



}

}

我可以收到从 firebase 控制台发送的通知。 我已将我的 firebase 库升级到最新的 3.0 版本。

我也收到以下警告。 'InstanceIDAPNSTokenType' 已弃用:请改用 FIRMessaging 的 APNSToken 属性。

请提供代码解决方案并给我服务器请求结构,以便我可以从邮递员那里测试它。

提前致谢。

【问题讨论】:

    标签: ios firebase swift3 firebase-cloud-messaging xcode8.2


    【解决方案1】:

    您可以尝试像这样设置 apn 令牌吗:

    FIRInstanceID.instanceID()
        .setAPNSToken(deviceToken, type: FIRInstanceIDAPNSTokenType.unknown)
    

    FIRInstanceID 设置APNSToken

    为应用程序设置 APNS 令牌。此 APNS 令牌将用于使用令牌或 tokenWithAuthorizedEntity:scope:options:handler 向 Firebase Messaging 注册。如果令牌类型设置为 FIRInstanceIDAPNSTokenTypeUnknown InstanceID 将读取配置文件以找出令牌类型。

    Firebase API reference

    它对我有用!

    编辑:

    使用 Firebase 4.0.0 版的方式发生了变化:

    Messaging.messaging()
        .setAPNSToken(deviceToken, type: MessagingAPNSTokenType.unknown)
    

    FIRMessaging API reference

    【讨论】:

    • FIRInstanceID 更改为 InstanceID,FIRInstanceIDAPNSTokenType 更改为 InstanceIDAPNSTokenType ..我已将 firebase 库升级到最新版本..
    • 您使用的是 iOS SDK 4.0.0 吗?这是 5 月 17 日发布的,所以我暂时不使用这个版本。您可以尝试使用:Messaging.messaging().apnsToken = deviceToken。它也许会解决你的问题。 Look at Firebase API reference
    • 我认为这是正确的做法:Messaging.messaging().setAPNSToken(deviceToken, type: MessagingAPNSTokenType.unknown)
    • 大家好,作为这些更改的作者,首选方法是您只使用属性设置器,例如Messaging.messaging().apnsToken deviceTokensetAPNSToken(_,type:) 是出于遗留原因。
    • 使用未解析的标识符“InstanceIDAPNSTokenType”
    【解决方案2】:

    我刚刚updated the Github sample app to reflect the API changes。对于那个很抱歉。我认为有些改变是通过了。现在设置 APNs 令牌的首选方法(如果您已禁用 swizzling)是:

    Messaging.messaging().apnsToken = deviceToken
    

    旧方法setAPNSToken:type: 会造成更多混乱,因为如果包含类型并且它确实与构建类型匹配,则 FCM 令牌将不起作用。如果您确实需要使用旧方法,我建议您使用“未知”枚举,它会进行自动检查。

    您的问题标题提到您没有收到数据消息,新的示例更改应该会显示这一点。接收数据报文的方式是:

    1. 通过设置启用直接通道:Messaging.messaging().shouldEstablishDirectChannel = true

    2. 实现FIRMessagingDelegatemessaging:didReceiveRemoteMessage方法。

    您可以查看的另一个示例应用程序是开源 FCM 存储库 here 的一部分。

    【讨论】:

    • 我试过 - Messaging.messaging().apnsToken = deviceToken - 但它希望我将其重铸为 Data 而不是 FB 文档中的新 NSData
    • @ErikGrosskurth 嗯,你能指出我的文档吗?也许文档需要更新。你用的是 Swift,对吧?
    • 我能够接收数据通知,但我没有收到通知横幅,以及当我的应用程序处于后台模式时我没有收到通知,一旦我打开我的应用程序,我可以收到通知但我没有为此获得横幅。
    • @user3066829 您能告诉我您通过 FCM HTTP API 发送的有效负载类型吗?您是否在 JSON 有效负载中包含“通知”键?
    猜你喜欢
    • 2019-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多