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

Posted

技术标签:

【中文标题】直接从设备向设备发送推送通知 swift 3【英文标题】:send push notification to device directly from a device swift 3 【发布时间】:2017-09-19 12:25:41 【问题描述】:

有没有办法直接使用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函数参数 【参考方案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

【讨论】:

以上是关于直接从设备向设备发送推送通知 swift 3的主要内容,如果未能解决你的问题,请参考以下文章

如何向 Azure 通知中心注册的每个设备发送不同的推送通知?

我们可以从 iOS 设备向 APNs 发送推送通知吗?

从服务器向所有设备发送推送通知

从 php 服务器向 ios 设备发送多个推送通知

如何在 Node JS 中使用 Amazon SNS 向 iOS 设备发送 VoIP 推送通知

从 Windows Phone 设备向 Web 服务发送推送通知