简体   繁体   English

直接从设备swift将推送通知发送到设备3

[英]send push notification to device directly from a device swift 3

Is there any way to send push notification from a device to device directly using https://fcm.googleapis.com/fcm/send . 是否可以使用https://fcm.googleapis.com/fcm/send直接将推送通知从设备发送到设备。

My code: 我的代码:

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()
}
let paramString  = ["to" : FCM_ID/UDID, "notification" : ["title" : NOTIFICATION_TITLE, "body" : NOTIFICATION_BODY], "data" : ["user" : USER_ID, "image" : IMAGE_URL, "extrainfo" : ANY_STRING]]

just replace your line with this one and push notification should deliver. 只需用这一行替换您的行,然后推送通知就会发出。

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

Old post but it's worth to add to accepted solution as it can be helping others. 旧帖子,但是值得添加已接受的解决方案,因为它可以帮助其他人。 You can check my post Push Notifications are delivered but didReceiveRemoteNotification is never called Swift or here didReceiveRemoteNotification function doesn't called with FCM notification server . 您可以检查我的Push Push Notifications是否已交付,但didReceiveRemoteNotification从未被称为Swift或在这里FCM通知服务器未调用didReceiveRemoteNotification函数 You must have "content_available": true in your notification definition or push notification service(with underscore) or your didReceiveRemoteNotification won't be called and you won't be able to use userInfo . 您必须具有"content_available": true在通知定义或推送通知服务(带有下划线)中为"content_available": true ,否则将不会调用didReceiveRemoteNotification并且您将无法使用userInfo

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

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