gpt4 book ai didi

ios - 火力地堡, swift : Send a push notification to specific user given device token

转载 作者:行者123 更新时间:2023-11-28 08:04:09 24 4
gpt4 key购买 nike

我有一个 Firebase Swift 聊天应用程序,我想在其中向特定用户发送推送通知。我已经捕获并可以访问用户的设备 token 。

所有引用资料都提到必须有一个“网络应用程序”来管理它,但我还没有设法找到这方面的任何具体示例。

  1. 是否需要一个网络应用程序来管理 Firebase 的推送通知?

  2. 如果是这样,是否有任何示例说明这是如何工作的?

谢谢。

最佳答案

  • 首先为 Firebase 云消息传递 进行所有配置。可以关注这个链接https://firebase.google.com/docs/cloud-messaging/ios/client
  • 现在您需要为要向其发送推送通知的关联用户访问 Firebase 注册 token 。您可以按照以下步骤获取此 token :
    1. 'Firebase/Messaging' pod 添加到您的项目。
    2. 在您的 AppDelegate.swift 文件中导入 FirebaseMessaging
    3. 使 MessagingDelegate 协议(protocol)符合您的 AppDelegate 类。
    4. 编写 didRefreshRegistrationToken 委托(delegate)方法并获取用户的注册 token :
  • 现在您已准备好向您的特定用户发送推送通知。发送通知如下:

    func sendPushNotification(payloadDict: [String: Any]) {
    let url = URL(string: "https://fcm.googleapis.com/fcm/send")!
    var request = URLRequest(url: url)
    request.setValue("application/json", forHTTPHeaderField: "Content-Type")
    // get your **server key** from your Firebase project console under **Cloud Messaging** tab
    request.setValue("key=enter your server key", forHTTPHeaderField: "Authorization")
    request.httpMethod = "POST"
    request.httpBody = try? JSONSerialization.data(withJSONObject: payloadDict, options: [])
    let task = URLSession.shared.dataTask(with: request) { data, response, error in
    guard let data = data, error == nil else {
    print(error ?? "")
    return
    }
    if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {
    print("statusCode should be 200, but is \(httpStatus.statusCode)")
    print(response ?? "")
    }
    print("Notfication sent successfully.")
    let responseString = String(data: data, encoding: .utf8)
    print(responseString ?? "")
    }
    task.resume()
    }
  • 现在调用上面的函数:

    let userToken = "your specific user's firebase registration token"
    let notifPayload: [String: Any] = ["to": userToken,"notification": ["title":"You got a new meassage.","body":"This message is sent for you","badge":1,"sound":"default"]]
    self.sendPushNotification(payloadDict: notifPayload)

关于ios - 火力地堡, swift : Send a push notification to specific user given device token,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45678212/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com