Home > database >  HTTP POST Request FCM (Swift) shows Error Code 401
HTTP POST Request FCM (Swift) shows Error Code 401

Time:10-24

can somebody help me with my code?

I'm slowly going crazy. I am in the process of integrating Firebase FCM into my app and would like to send push messages. From one device to another.

This is my code:

class PushNotificationSender {

let key = NotificationConstants().key_2

func sendPushNotification(to token: String, title: String, body: String) {
    let urlString = "https://fcm.googleapis.com/fcm/send"
    let url = NSURL(string: urlString)!
    let paramString: [String : Any] = ["to" : token,
                                       "notification" : [
                                        "body" : body,
                                        "title" : title,
                                        "sound" : true
                                       ]
    ]

    
    let request = NSMutableURLRequest(url: url as URL)
    request.httpMethod = "POST"
    request.httpBody = try? JSONSerialization.data(withJSONObject:paramString, options: [.prettyPrinted])
    request.setValue("key=\(self.key)", forHTTPHeaderField: "Authorization")
    request.setValue("application/json", 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)
            print(error as Any)
            print(err )
            print(response as Any)
            print(request)
        }
    }
    task.resume()
    print("Pushnotification Sent")
}

}

And this is what I receive, when I send messages:

    Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around line 1, column 0." UserInfo={NSDebugDescription=Invalid value around line 1, column 0., NSJSONSerializationErrorIndex=0}
Optional(<NSHTTPURLResponse: 0x2828da4c0> { URL: https://fcm.googleapis.com/fcm/send } { Status Code: 401, Headers {
    "Alt-Svc" =     (
        "h3=\":443\"; ma=2592000,h3-29=\":443\"; ma=2592000,h3-Q050=\":443\"; ma=2592000,h3-Q046=\":443\"; ma=2592000,h3-Q043=\":443\"; ma=2592000,quic=\":443\"; ma=2592000; v=\"46,43\""
    );
    "Cache-Control" =     (
        "private, max-age=0"
    );
    "Content-Encoding" =     (
        gzip
    );
    "Content-Length" =     (
        130
    );
    "Content-Type" =     (
        "text/html; charset=UTF-8"
    );
    Date =     (
        "Fri, 21 Oct 2022 16:55:01 GMT"
    );
    Expires =     (
        "Fri, 21 Oct 2022 16:55:01 GMT"
    );
    Server =     (
        GSE
    );
    "content-security-policy" =     (
        "frame-ancestors 'self'"
    );
    "x-content-type-options" =     (
        nosniff
    );
    "x-frame-options" =     (
        SAMEORIGIN
    );
    "x-xss-protection" =     (
        "1; mode=block"
    );
} })

I really don't know what's wrong. Referring to Firebase Documentation error status 401 means "no authorization".

I configured Firebase as follows:

Firebase Configuration Part 1

Firebase Cloud Messaging API (V1)

Firebase Configuration Part 2

APNs authentication key

CodePudding user response:

The server key was invalid. Firebase version 9.6.0

Tips for Troubleshooting:

  • Check Payload
  • Check Server Key
  • Check if Cloud Messaging API is enabled
  • Check HTTP Request

Firebase Links for troubleshooting:

  1. Messaging Concept
  2. FCM:Send Method
  • Related