当前位置: 首页 > 知识库问答 >
问题:

未使用firebase云消息发送的swift向iPhone发送通知

裴楚青
2023-03-14

我想使用firebase云消息将通知从我的应用程序发送到另一个应用程序。所以我使用这个方法retrieveFCMToken(forSenderID:senderid)来处理这个过程。我将以下代码添加到我的应用程序委托中:

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    print("APNs token retrieved: \(deviceToken)")
    Messaging.messaging().apnsToken = deviceToken

    let senderid = "<YOUR SENDER ID>"
    Messaging.messaging().retrieveFCMToken(forSenderID: senderid) {(message,Error) in  
        print("message",message!)
    }
}

这是我的应用程序代理:

import UIKit
import UserNotifications

import Firebase

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

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

    func application(_ application: UIApplication,
                     didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

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

        // [END register_for_notifications]
        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
        // 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)")
    }

    // 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 FCM registration token.
    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        print("APNs token retrieved: \(deviceToken)")
        Messaging.messaging().apnsToken = deviceToken

        //Code for sending to other sender ID
        let senderid = "xxxxxxxx"
        Messaging.messaging().retrieveFCMToken(forSenderID: senderid) {(message,Error) in  // here i am generating the token for other sender id project
            print("message",message!)
        }
    }
}

// [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 html" target="_blank">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()
    }
}
// [END ios_10_message_handling]

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

        let dataDict:[String: String] = ["token": fcmToken]
        NotificationCenter.default.post(name: Notification.Name("FCMToken"), object: nil, userInfo: dataDict)
        // 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]
}

我遵循这个场景:我有两个应用程序,分别是“A”和“B”。我想将通知从应用程序“A”发送到应用程序“B”。因此,我将应用程序A的发件人id放入应用程序B代理文件中,并使用应用程序B生成应用程序A的注册令牌。因此,在向应用程序B发送通知时,我将生成的注册令牌放入应用程序A的firebase云消息控制台。但应用程序B未收到通知。如何解决这个错误?我在firebase cloud messaging中的两个应用程序数据库中上传了有效的APN认证密钥。

暂时还没有答案

 类似资料:
  • 我刚开始使用Firebase云消息。我建了一个IOS应用来接收推送通知。应用程序运行良好。我从Firebase控制台发送消息,它们会正确显示。 我的问题是:我可以向所有设备发送一条消息吗(就像我可以在控制台中做的那样)?我是的,怎么会这样? 提前道谢!

  • 我正在尝试为Web设置Firebase云消息传递。我成功地对其进行了正确初始化并获得了令牌: manifest.json与gcm_sender_id 我可以看到我在控制台中得到令牌,所以我试图验证它,并通过邮递员发送我的第一个通知-这里是留档。 发布网址:https://fcm.googleapis.com/v1/projects/PROJECTID/messages:发送授权:无授权 标题 Bo

  • null 当我确实从Firebase云消息发送给自己一条测试消息时,它确实工作正常,并且成功地向每个设备发送了一个推送通知。 例如,以下是 null

  • 我正在尝试使用Postman通过云消息服务发送一次推送通知。 这是一个用于相同目的的工作命令,我将其用作参考。 到目前为止我所做的。。 1-适当设置标题 2-在Body,我使用 执行时,我返回

  • 我正在制作一个android应用程序,其中我使用firebase身份验证来验证用户,使用firestore来存储一些用户数据。我想让用户有一个设置,他们可以订阅推送通知。如果他们订阅,我希望我的应用程序定期向他们发送通知,比如每6小时一次。目前,我已经使用firebase控制台测试了推送通知,它看起来工作正常。以下是我到目前为止的< code > myfirebasemesagingservice

  • 有人知道一种从firebase控制台发送click_action的方法吗? 我只想发送click_action按钮来使用通知,即使应用程序关闭或在后台。