直接从设备swift 3

时间:2017-09-19 12:25:42

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

有没有办法直接使用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()
}

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:-1)

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