ios - Firebase 云消息传递不适用于 IOS

标签 ios swift firebase firebase-cloud-messaging

所以我已经尝试解决这个问题一段时间了,我已经按照设置指南进行了几次操作,但我什至无法让从 firebase 控制台发送的推送通知显示出来。我设置并运行了 Phone Auth,这需要推送通知和 APN 设置,与 FCM 相同。这是我的 AppDelegate 文件:

//
//  AppDelegate.swift
//  texter
//
//  Created by Johnathan Saunders on 3/28/17.
//  Copyright © 2017 Johnathan Saunders. All rights reserved.
//
import UIKit
import Firebase

import UserNotifications
@UIApplicationMain
class AppDelegate:  UIResponder, UIApplicationDelegate,MessagingDelegate {

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


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

        FirebaseApp.configure()

        // [START set_messaging_delegate]
        Messaging.messaging().delegate = self
        // [END set_messaging_delegate]
        // 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()
        let token = Messaging.messaging().fcmToken
        print("FCM token: \(token ?? "")")
        // [END register_for_notifications]

        return true
    }

    func applicationWillResignActive(_ application: UIApplication) {
        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
        // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
    }

    func applicationDidEnterBackground(_ application: UIApplication) {
        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    }

    func applicationWillEnterForeground(_ application: UIApplication) {
        // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
    }

    func applicationDidBecomeActive(_ application: UIApplication) {
        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    }

    func applicationWillTerminate(_ application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    }

    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        // Pass device token to auth.
        let firebaseAuth = Auth.auth()

        //At development time we use .sandbox
        firebaseAuth.setAPNSToken(deviceToken, type: AuthAPNSTokenType.sandbox)
        print("APNs token retrieved: \(deviceToken)")
        InstanceID.instanceID().setAPNSToken(deviceToken, type: .prod)
        // With swizzling disabled you must set the APNs token here.
        Messaging.messaging().apnsToken = deviceToken
        //At time of production it will be set to .prod
    }


    //notifcation stuff

    // [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
        // With swizzling disabled you must let Messaging know about the message, for Analytics
         Messaging.messaging().appDidReceiveMessage(userInfo)
        // 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
        // With swizzling disabled you must let Messaging know about the message, for Analytics
         Messaging.messaging().appDidReceiveMessage(userInfo)
        // 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)")
    }



    // [END ios_10_message_handling]


    // [START refresh_token]
    func messaging(_ messaging: Messaging, didRefreshRegistrationToken fcmToken: String) {
        print("Firebase registration token: \(fcmToken)")

        // TODO: If necessary send token to application server.
        // Note: This callback is fired at each app startup and whenever a new token is generated.
    }
    // [END refresh_token]
    // [START ios_10_data_message]
    // Receive data messages on iOS 10+ directly from FCM (bypassing APNs) when the app is in the foreground.
    // To enable direct data messages, you can set Messaging.messaging().shouldEstablishDirectChannel to true.
    func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) {
        print("Received data message: \(remoteMessage.appData)")

    }
    // [END ios_10_data_message]

    func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
        print("Firebase registration token: \(fcmToken)")

        // TODO: If necessary send token to application server.
        // Note: This callback is fired at each app startup and whenever a new token is generated.
    }


}

// [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

        // With swizzling disabled you must let Messaging know about the message, for Analytics
        // Messaging.messaging().appDidReceiveMessage(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([])
    }

    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()
    }

}

我下载/生成的证书和 key 是:enter image description here 证书、标识符和配置文件部分如下所示: enter image description here enter image description here enter image description here 在 firebase 的设置中,它看起来像这样:enter image description here

最佳答案

对于 FCM,您不需要使用 InstanceIDFirabaseAuth 并且没有它们我可以使用从我的应用程序以编程方式发送 APNS 到订阅的主题

我的 pod 只包含

pod 'Firebase/Messaging'

工作代码如下:

 //MARK:- Push Notification
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    //  Register.
    let deviceTokenString = deviceToken.reduce("", {$0 + String(format: "%02X", $1)})
    print("deviceTokenString: \(deviceTokenString)")
    self.apnsToken = deviceTokenString

    //set apns token in messaging
    Messaging.messaging().apnsToken = deviceToken

    //get FCM token
    if let token = Messaging.messaging().fcmToken {
        self.fcmToken = token
        print("FCM token: \(token)")
    }

    //subscribe to topic to send message to multiple device
    self.subscribeToTopic()
}

通过如下给出的主题以编程方式将 APNS 发送到所有设备:

func sendPushMessage(todoItem:TodoItem, isAdded:Bool = true) {

  let url = URL(string: "https://fcm.googleapis.com/fcm/send")!
  var request = URLRequest(url: url)
  request.httpMethod = "POST"
  request.setValue("application/json", forHTTPHeaderField: "Content-Type")
  let strKey:String = "Here FCM Server Key"
  request.setValue("key=\(strKey)", forHTTPHeaderField: "Authorization")

  var message:String = ""
  if isAdded {
    message = "Todo with title '\(todoItem.title)' added"
  }
  else{
    message = "Todo with title '\(todoItem.title)' removed"
  }

  let dictData = ["to":"/topics/alldevices","priority":"high","notification":["body":message,"title":"Community","badge":"1"]] as [String : Any]

  do {
     let jsonData = try JSONSerialization.data(withJSONObject: dictData, options: .prettyPrinted)
     // here "jsonData" is the dictionary encoded in JSON data

     request.httpBody = jsonData

     let task = URLSession.shared.dataTask(with: request, completionHandler: { (responseData: Data?, response: URLResponse?, error: Error?) in

        let strData :String = String(data: responseData!, encoding: String.Encoding.utf8)!
        print("data : \(strData)")
        NSLog("\(String(describing: response) )")
    })
    task.resume()

  } catch {
    print(error.localizedDescription)
  }
}

另请参阅 https://www.appcoda.com/firebase-push-notifications/

关于ios - Firebase 云消息传递不适用于 IOS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47208312/

相关文章:

ios - NSURLCache Alamofire 删除缓存响应

javascript - Firebase 托管后,出现错误 "firebase is not defined"

Javascript:Cloud Firestore 合并正在替换数据

ios - Swift 中指针的替代品?

c# - ReplayKit 制作的视频在 Xamarin 中不断跳帧

swift - UIButton的自定义绘制

swift - 当用户点击屏幕时创建多个 UIView

ios - 使用 Swift 和 Firebase 聊天应用程序逻辑

ios - 圆角 View 在 iOS 9 中不起作用

ios - 未始终为 UIPageControl 触发 UIControlEventValueChanged 事件