我无法接收iOS swift 3的数据通知

时间:2017-05-23 07:54:17

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

我正在关注firebase提供的sampler项目。 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版本。

我也得到以下警告。 &#39; InstanceIDAPNSTokenType&#39;不推荐使用:改为使用FIRMessaging的APNSToken属性。

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

提前致谢。

2 个答案:

答案 0 :(得分:12)

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

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

FIRInstanceID setAPNSToken

     

为应用程序设置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

答案 1 :(得分:9)

我刚刚updated the Github sample app to reflect the API changes。对于那个很抱歉。我认为其中一些变化已经过去了。设置APN令牌的首选方法(如果您已禁用调配)现在是:

Messaging.messaging().apnsToken = deviceToken

旧方法setAPNSToken:type:导致更多混淆,因为如果包含类型且匹配构建类型,则FCM令牌将无效。如果您确实需要使用旧方法,我建议使用“未知”枚举,它会自动检查。

您的问题标题提到您没有收到数据消息,而新的示例更改应该显示出来。接收数据消息的方式是:

  1. 通过设置:Messaging.messaging().shouldEstablishDirectChannel = true

  2. 启用直接频道
  3. 实施FIRMessagingDelegatemessaging:didReceiveRemoteMessage方法。

  4. 您可以查看的另一个示例应用是开源FCM回购here的一部分。