簡體   English   中英

我無法接收iOS swift 3的數據通知

[英]I am not able to receive data notification iOS swift 3

我正在關注firebase提供的sampler項目。 Firebase雲消息傳遞

我的應用代表是

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屬性。

請提供代碼解決方案,並給我服務器請求結構,以便我可以從郵遞員測試它。

提前致謝。

您可以嘗試像這樣設置apn令牌:

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

FIRInstanceID setAPNSToken

為應用程序設置APNS令牌。 此APNS令牌將用於使用令牌或tokenWithAuthorizedEntity:scope:options:handler向Firebase Messaging注冊。 如果令牌類型設置為FIRInstanceIDAPNSTokenTypeUnknown InstanceID將讀取配置配置文件以找出令牌類型。

Firebase API參考

它對我有用!

編輯:

使用Firebase版本4.0.0時,執行此操作的方式已更改:

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

FIRMessaging API參考

我剛剛更新了Github示例應用程序以反映API更改 對於那個很抱歉。 我認為其中一些變化已經過去了。 設置APN令牌的首選方法(如果您已禁用調配)現在是:

Messaging.messaging().apnsToken = deviceToken

舊方法setAPNSToken:type:引起了更多的混淆,因為如果包含類型並且它與構建類型匹配,則FCM令牌將不起作用。 如果您確實需要使用舊方法,我建議使用“未知”枚舉,它將進行自動檢查。

您的問題標題提到您沒有收到數據消息,新的示例更改應該顯示。 接收數據消息的方式是:

  1. 通過設置啟用直接通道: Messaging.messaging().shouldEstablishDirectChannel = true

  2. 實現FIRMessagingDelegatemessaging:didReceiveRemoteMessage FIRMessagingDelegate方法。

您可以看到的另一個示例應用程序是這里的開源FCM回購的一部分。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM