【发布时间】:2020-02-17 15:27:45
【问题描述】:
我遇到了一个非常奇怪的问题,从 Firebase 控制台发送的通知正在正确传递,因此这意味着项目已配置并且证书正确,但是当我从应用程序发送通知时它不起作用。我正在使用以下方法发送通知。
func sendPushNotification(to token: String, title: String, body: String, Type: String) {
let urlString = "https://fcm.googleapis.com/fcm/send"
let url = NSURL(string: urlString)!
let paramString: [String : Any] =
[
"message" :[
"to" : token,
"notification" : ["title" : title, "body" : body],
"data" : ["notification_type": Type]
],
"to" : token
]
print(paramString)
let request = NSMutableURLRequest(url: url as URL)
request.httpMethod = "POST"
request.httpBody = try? JSONSerialization.data(withJSONObject:paramString, options: [.prettyPrinted])
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue("key=AAAApQ9EAjg:XXXX", forHTTPHeaderField: "Authorization")
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()
}
我也试过用下面的方法通过curl发送
<?php
/**
* Created by PhpStorm.
* User: ussaidiqbal
* Date: 2020-02-17
* Time: 19:45
*/
$url = "https://fcm.googleapis.com/fcm/send";
$token = "eMIK6wGOTUUutqp62vEIr-:XXXXXX";
$serverKey = 'AIzaSyCJFUydXXXXXXXXXX';
$title = "Title";
$body = "Body of the message";
$notification = array('title' =>$title , 'text' => $body, 'sound' => 'default', 'badge' => '1');
$arrayToSend = array('to' => $token, 'notification' => $notification,'priority'=>'high');
$json = json_encode($arrayToSend);
$headers = array();
$headers[] = 'Content-Type: application/json';
$headers[] = 'Authorization: key='. $serverKey;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST,
"POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
curl_setopt($ch, CURLOPT_HTTPHEADER,$headers);
//Send the request
$response = curl_exec($ch);
//Close request
if ($response === FALSE) {
die('FCM Send Error: ' . curl_error($ch));
}
curl_close($ch);
我也尝试使用以下有效负载通过 PostMan 发送
{
"notification":{
"title": "XXXXX",
"body": "XXXXX"
},
"to": "XXXXXXX"
}
这是请求的响应
{
"multicast_id": 36126XXXXXXXX,
"success": 1,
"failure": 0,
"canonical_ids": 0,
"results": [
{
"message_id": "0:1581960379105057~~~~~~~~~~"
}
]
}
上述方法似乎都不起作用,我做错了什么? 我已经尝试过 Legacy server key 和 Server key 但没有运气。有没有人遇到过这样的问题?
【问题讨论】:
-
我认为你的问题是
setValue,你应该使用addValue。 SetValue 将替换所有值! -
我也试过 addValue
-
您的“to”标记是否正确?您是否使用了 FirebaseMessage 令牌?不是 APN 令牌?用 Postman 试试,你会得到什么作为响应或状态码?
-
func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String)这里生成的token我用过了 -
但是您没有将 PushNoti 发送到同一设备!?如果应用程序是 1. 打开,2. 模拟器(模拟器可能会更改),3. 如果您向自己发送推送,则通知将不会发送。用 Postman 试试。是最好的办法
标签: swift firebase firebase-cloud-messaging