【问题标题】:send push notification to device directly from a device swift 3直接从设备向设备发送推送通知 swift 3
【发布时间】:2026-01-15 20:50:02
【问题描述】:

有没有办法直接使用https://fcm.googleapis.com/fcm/send从设备向设备发送推送通知。

我的代码:

func sendPushNotification(toUser: String, message: String) {
    let urlString = "https://fcm.googleapis.com/fcm/send"
    let url = NSURL(string: urlString)!
    let paramString  = "to="

    let request = NSMutableURLRequest(url: url as URL)
    request.httpMethod = "POST"
    request.httpBody = paramString.data(using: String.Encoding.utf8)!
    request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")

    let task =  URLSession.shared.dataTask(with: request as URLRequest)  { (data, response, error) in
        do {
            if let jsonData = data {
                if let jsonDataDict  = try JSONSerialization.jsonObject(with: jsonData, options: JSONSerialization.ReadingOptions.allowFragments) as? [String: AnyObject] {
                    NSLog("Received data:\n\(jsonDataDict))")
                }
            }
        } catch let err as NSError {
            print(err.debugDescription)
        }
    }
    task.resume()
}

【问题讨论】:

  • 你从不使用toUser函数参数

标签: ios firebase swift3 push-notification firebase-cloud-messaging


【解决方案1】:
let paramString  = ["to" : FCM_ID/UDID, "notification" : ["title" : NOTIFICATION_TITLE, "body" : NOTIFICATION_BODY], "data" : ["user" : USER_ID, "image" : IMAGE_URL, "extrainfo" : ANY_STRING]]

只需将您的线路替换为这条线路,推送通知就会送达。

在此处了解更多信息...https://firebase.google.com/docs/cloud-messaging/server

【讨论】:

  • 你能帮我创建NOTIFICATION_BODY吗
  • 它只是一个简单的字符串。它是显示在标题下方的通知横幅上的消息。大写字母中的所有内容都只是您需要替换的字符串。
  • 我想在正文中发送一些内容,例如图片 url、用户 ID
  • 那么你还需要添加数据键值。更新了我的答案,请检查。
  • 如何以及在何处包含我们的服务器授权密钥??
【解决方案2】:

旧帖子,但值得添加到已接受的解决方案中,因为它可以帮助他人。你可以查看我的帖子Push Notifications are delivered but didReceiveRemoteNotification is never called Swift 或这里didReceiveRemoteNotification function doesn't called with FCM notification server。 您的通知定义或推送通知服务(带下划线)中必须有"content_available": true,否则您的didReceiveRemoteNotification 将不会被调用并且您将无法使用userInfo

【讨论】:

    最近更新 更多