Swift 如果发送的不是Firebase控制台,则不会传递Firebase通知
我面临一个非常奇怪的问题,从Firebase控制台发送的通知被正确地传递,因此这意味着项目已配置,证书正确,但当我从应用程序发送通知时,它不起作用。我正在使用以下方法发送通知Swift 如果发送的不是Firebase控制台,则不会传递Firebase通知,swift,firebase,firebase-cloud-messaging,Swift,Firebase,Firebase Cloud Messaging,我面临一个非常奇怪的问题,从Firebase控制台发送的通知被正确地传递,因此这意味着项目已配置,证书正确,但当我从应用程序发送通知时,它不起作用。我正在使用以下方法发送通知 func sendPushNotification(to token: String, title: String, body: String, Type: String) { let urlString = "https://fcm.googleapis.com/fcm/send" le
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);
这是请求的响应
{
"multicast_id": 36126XXXXXXXX,
"success": 1,
"failure": 0,
"canonical_ids": 0,
"results": [
{
"message_id": "0:1581960379105057~~~~~~~~~~"
}
]
}
上述方法似乎都不起作用,我做错了什么?
我尝试了传统服务器密钥和服务器密钥,但没有成功。有人曾经遇到过这样的问题吗?结构通知结构:可编码{
struct NotificationStruct: Codable {
var notification: NotificationBodyStruct?
var to: String?
var time_to_live = 60000
}
struct NotificationBodyStruct: Codable {
var title: String?
var text: String?
var sound: String?
}
func sendNotificationtoken: String, name: String, completion: @escaping(Bool) -> Void) {
do {
let noti = NotificationStruct(notification: NotificationBodyStruct(title: name, text: text, sound: "default"), to: "\(token)", time_to_live: 6000)
let body = try JSONEncoder().encode(noti)
makeConnection(body: body) { (success) in
DispatchQueue.main.async {
completion(true)
}
}
} catch {
print("sendNotification \(error.localizedDescription)")
DispatchQueue.main.async {
completion(false)
}
}
}
private func makeConnection(body: Data, completion: @escaping(Bool) -> Void) {
guard let url = URL(string: "http://gcm-http.googleapis.com/gcm/send") else {
completion(false)
return
}
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.allHTTPHeaderFields = ["Content-Type": "application/json", "Authorization": "key=A**YOUR_KEY**A"]
request.httpBody = body
let session = URLSession.shared
let dataTask = session.dataTask(with: request, completionHandler: { (data, response, error) -> Void in
guard error == nil else {
print("Error NotificationHelper ", error?.localizedDescription ?? "")
completion(false)
return
}
guard let httpResponse = response as? HTTPURLResponse else {
print("httpResponse error NotificationHelper ")
completion(false)
return
}
guard httpResponse.statusCode < 500 else {
print("Error NotificationHelper < 500 \(httpResponse)", response ?? "" )
completion(false)
return
}
guard (httpResponse.statusCode >= 200 && httpResponse.statusCode <= 299) else {
print("error NotificationHelper >= 200 && httpResponse.statusCode <= 299 \(httpResponse)", response ?? "" )
completion(false)
return
}
guard let _ = data else {
print("Problem with Data NotificationHelper ")
completion(false)
return
}
completion(true)
})
dataTask.resume()
}
var通知:NotificationBodyStruct?
变量到:字符串?
var时间到现场=60000
}
结构NotificationBodyStruct:可编码{
变量标题:字符串?
变量文本:字符串?
声音:弦?
}
func sendNotificationtoken:String,name:String,completion:@escaping(Bool)->Void){
做{
let noti=NotificationStruct(通知:NotificationBodyStruct(标题:名称,文本:文本,声音:“默认”),to:“\(令牌)”,time\u to\u live:6000)
让body=try JSONEncoder().encode(noti)
中的makeConnection(body:body){(success)
DispatchQueue.main.async{
完成(真)
}
}
}抓住{
打印(“sendNotification\(error.localizedDescription)”)
DispatchQueue.main.async{
完成(假)
}
}
}
私有func makeConnection(主体:数据,完成:@escaping(Bool)->Void){
guard let url=url(字符串:http://gcm-http.googleapis.com/gcm/send)其他{
完成(假)
返回
}
var-request=URLRequest(url:url)
request.httpMethod=“POST”
request.allHTTPHeaderFields=[“内容类型”:“应用程序/json”,“授权”:“key=A**YOUR_key**A”]
request.httpBody=body
让session=URLSession.shared
让dataTask=session.dataTask(with:request,completionHandler:{(数据,响应,错误)->Void in
保护错误==nil else{
打印(“错误通知助手”,错误?.localizedDescription??)
完成(假)
返回
}
guard let httpResponse=响应为?HTTPURLResponse else{
打印(“httpResponse错误通知帮助程序”)
完成(假)
返回
}
guard httpResponse.statusCode<500其他{
打印(“错误通知帮助程序<500\(httpResponse)”,响应??)
完成(假)
返回
}
guard(httpResponse.statusCode>=200&&httpResponse.statusCodestruct NotificationStruct:Codable{
var通知:NotificationBodyStruct?
变量到:字符串?
var时间到现场=60000
}
结构NotificationBodyStruct:可编码{
变量标题:字符串?
变量文本:字符串?
声音:弦?
}
func sendNotificationtoken:String,name:String,completion:@escaping(Bool)->Void){
做{
let noti=NotificationStruct(通知:NotificationBodyStruct(标题:名称,文本:文本,声音:“默认”),to:“\(令牌)”,time\u to\u live:6000)
让body=try JSONEncoder().encode(noti)
中的makeConnection(body:body){(success)
DispatchQueue.main.async{
完成(真)
}
}
}抓住{
打印(“sendNotification\(error.localizedDescription)”)
DispatchQueue.main.async{
完成(假)
}
}
}
私有func makeConnection(主体:数据,完成:@escaping(Bool)->Void){
guard let url=url(字符串:http://gcm-http.googleapis.com/gcm/send)其他{
完成(假)
返回
}
var-request=URLRequest(url:url)
request.httpMethod=“POST”
request.allHTTPHeaderFields=[“内容类型”:“应用程序/json”,“授权”:“key=A**YOUR_key**A”]
request.httpBody=body
让session=URLSession.shared
让dataTask=session.dataTask(with:request,completionHandler:{(数据,响应,错误)->Void in
保护错误==nil else{
打印(“错误通知助手”,错误?.localizedDescription??)
完成(假)
返回
}
guard let httpResponse=响应为?HTTPURLResponse else{
打印(“httpResponse错误通知帮助程序”)
完成(假)
返回
}
guard httpResponse.statusCode<500其他{
打印(“错误通知帮助程序<500\(httpResponse)”,响应??)
完成(假)
返回
}
guard(httpResponse.statusCode>=200&&httpResponse.statusCode我还认为您的paramString具有错误的属性。请尝试:
let paramString: [String : Any] = [
"to" : token,
"notification" : ["title" : title, "text" : body],
"time_to_live" : 60000,
"sound" : "default"
]
我还认为您的paramString具有错误的属性。请尝试:
let paramString: [String : Any] = [
"to" : token,
"notification" : ["title" : title, "text" : body],
"time_to_live" : 60000,
"sound" : "default"
]
因此,在花费了大量时间之后,我找到了它,并且一切正常。因此,如果任何其他人面临此问题,他们可以通过打开您的AppDelegate.swift
文件来解决,请找到一个函数didRegisterForRemoteNotificationsWithDeviceToken
,并替换为以下内容
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
print("APNs token retrieved: \(deviceToken)")
// With swizzling disabled you must set the APNs token here.
Messaging.messaging().apnsToken = deviceToken
}
完成此操作后,一切似乎都正常工作。因此,在花费了大量时间之后,我找到了它,并且一切正常工作。因此,如果其他人面临此问题,他们可以通过打开您的AppDelegate.swift
文件来解决,请找到一个函数didRegisterforremotentificationswithDeviceToken
,并替换为以下内容
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
print("APNs token retrieved: \(deviceToken)")
// With swizzling disabled you must set the APNs token here.
Messaging.messaging().apnsToken = deviceToken
}
完成此操作后,一切似乎都正常。我认为您的问题是setValue
,您应该使用addValue
。setValue将替换所有值!我也尝试了addValue!您的“to”标记正确吗?您使用了FirebaseMessage标记吗?不是APN标记?请与Postman一起尝试,您得到了什么