私はfirebaseが提供するサンプラープロジェクトをフォローしています。 Firebase Cloud Messagingサンプル
私のアプリデリゲートは
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を使用してFirebaseMessagingに登録するために使用されます。トークンタイプがFIRInstanceIDAPNSTokenTypeUnknownに設定されている場合、InstanceIDはプロビジョニングプロファイルを読み取り、トークンタイプを見つけます。
それは私のために働いています!
編集:
Firebaseバージョン4.0.0では、その方法が変更されました。
Messaging.messaging()
.setAPNSToken(deviceToken, type: MessagingAPNSTokenType.unknown)
私はちょうど APIの変更を反映するようにGithubサンプルアプリを更新しました 。申し訳ありません。いくつかの変更はすり抜けたと思います。 (スウィズリングを無効にしている場合)APNトークンを設定するための推奨される方法は次のとおりです。
_Messaging.messaging().apnsToken = deviceToken
_
古いメソッドである_setAPNSToken:type:
_は、タイプが含まれていてnotがビルドのタイプと一致した場合、FCMトークンであるため、さらに混乱を引き起こしていました。動作しません。古い方法を使用する必要がある場合は、自動チェックを行う「不明」列挙型を使用することをお勧めします。
質問のタイトルに、データメッセージを受信していないことが記載されており、新しいサンプルの変更でそれが示されるはずです。データメッセージを受信する方法は次のとおりです。
次のように設定して、直接チャネルを有効にします。Messaging.messaging().shouldEstablishDirectChannel = true
FIRMessagingDelegate
メソッドと_messaging:didReceiveRemoteMessage
_メソッドを実装します。
あなたが見ることができるもう一つのサンプルアプリは、オープンソースのFCMリポジトリの一部です ここ 。