简体   繁体   English

Firebase Cloud Messaging无法在IOS上运行

[英]Firebase Cloud Messaging not working on IOS

So I have been trying to figure this out for a while I have followed the set up guide a few times and I can't even get the push notifications sent form the firebase console to show up. 因此,我尝试解决这一问题已经有一段时间了,我已经几次遵循设置指南,甚至无法从Firebase控制台发送推送通知来显示。 I have Phone Auth set up and working, which required push notifications and APN set up, same as FCM. 我已经设置并工作了电话验证,与FCM一样,它需要设置推送通知和APN。 Here is my AppDelegate file: 这是我的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()
    }

}

The certs and keys I downloaded/ generated are: 我下载/生成的证书和密钥是: 在此处输入图片说明 The Certificates, Identifiers & Profiles section looks like this: 证书,标识符和配置文件部分如下所示: 在此处输入图片说明 在此处输入图片说明 在此处输入图片说明 In firebase's setting its looks like this: 在firebase的设置中,其外观如下所示: 在此处输入图片说明

For FCM, you don't need to use InstanceID and FirabaseAuth and without that I am able use send APNS programmatically from my application to subscribed topic 对于FCM,您不需要使用InstanceIDFirabaseAuth ,否则,我可以使用从应用程序以编程方式将APNS发送到订阅的主题

My pod contains only 我的广告连播仅包含

pod 'Firebase/Messaging'

Working code is given below : 工作代码如下:

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

Send APNS to all devices programatically through topic like given below : 通过以下主题以编程方式将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)
  }
}

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM