【问题标题】:Firebase Notifications not being delivered if sent other than firebase console如果发送 Firebase 控制台以外的 Firebase 通知,则不会发送
【发布时间】: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 keyServer 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


【解决方案1】:
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()
}

【讨论】:

  • 我返回 true 但同样没有消息传递!
【解决方案2】:

我还认为您的 paramString 具有错误的属性。试试看:

        let paramString: [String : Any] = [
            "to" : token,
            "notification" : ["title" : title, "text" : body],
            "time_to_live" : 60000,
            "sound" : "default"
        ]

【讨论】:

    【解决方案3】:

    所以在花了很多时间后,我想通了,一切正常。因此,如果其他人遇到此问题,他们可以通过打开您的 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
        }
    

    做完这一切似乎一切正常。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-08-24
      • 2017-11-23
      • 1970-01-01
      • 2018-11-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多