我将非常感谢推送通知方面的帮助。我的应用程序有一个聊天功能,用户可以在其中直接相互发送短信。但如果没有推送通知,它就没有多大意义。这一切都是在 Firebase 上设置的。如何将推送通知从特定设备发送到特定设备?由于 Stackoverflow 上的推荐,我确实尝试了 Firebase Notifications 和 OneSignal。但我只能直接触发来自 Firebase 或 OneSignal 的通知,而不是从特定设备到特定设备的通知。
有人有这方面的经验吗?
最佳答案
如果您的数据存储在 Firebease 中,我也会使用 Cloud Messaging 进行推送通知。有多种方法可以实现这个消息通知功能,我会继续我认为最简单的一种。
假设您使用的是 FCM你有configured your app
首先您需要存储用户设备的 token ,这将与每个用户信息一起存储为字符串:
let token = Messaging.messaging().fcmToken
因此,在您的 Firebase 数据库中,在您的每个用户对象数据中,您将有一个存储带有 token 的字符串的键,如果您希望用户在多个设备上接收通知,则必须存储用户的多个 token 使用一个字符串数组,甚至是一个对象数组并存储设备类型等。这是您的选择和您的需求。
理想的推送通知环境通常由一个中间服务器组成,它接收请求并管理并将通知发送给相应的用户,在这种情况下你可以跳过这个并直接从你的应用程序发送,使用FCM POST request service :
如何构建 FCM POST 请求以发送通知的示例:
let url = URL(string: "https://fcm.googleapis.com/fcm/send")!
var request = URLRequest(url: url)
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue("key=--HERE-GOES-YOUR-API-KEY--", forHTTPHeaderField: "Authorization")
request.httpMethod = "POST"
这里你放的不是数据,阅读docs to understand all the keys和您可以发送的变量,您需要发出先前的 firebase 请求,您可以在其中获取设备 token 。
var notData: [String: Any] = [
"to" : "HERE YOU PUT THE DEVICE TOKEN(s)",
"notification": [
title : "not title",
body : "not body",
icon : "not icon"
],
"data": [
//More notification data.
]
]
然后你发送post请求,如果通知成功它会返回一个对象和更多的数据。
request.httpBody = notData.data(using: .utf8)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else { // check for fundamental networking error
print("error=\(error)")
return
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 { // check for http errors
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(response)")
}
let responseString = String(data: data, encoding: .utf8)
print("responseString = \(responseString)")
}
task.resume()
我一直在为一个移动原生应用程序和一个 React 网络应用程序使用相同的解决方案,它的效果非常好。
关于ios - 使用 Firebase iOS Swift 将通知从特定设备推送到特定设备,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47041574/