inputting json to my http request in Swift and getting errors, but perfectly valid in jsonlint.com

106 Views Asked by At

So my goal is to be able to trigger a notification without getting a NSCocoaErrorDomain error. Before this issue, I sent a notification to my single device using this json data in the http request:

let paramString: [String : Any] = ["to" : token,
                                       "notification" : ["title" : title, "body" : body],
                                       "data" : ["user" : "test_id"]
    ]

This worked perfectly fine and is basically equivalent to the image below, but with a notification object added in. Firebase docs

Now I wanted to step up and send a notification to people subscribed to a topic, so I changed the code up a bit as well as the url, but when I pressed the button and the code ran, I got a NSCocoaErrorDomain Code = 3840 meaning my json was in an invalid format.

NEW EDITSo this is the function I use and the json I had in my http request:

func sendNotificationToUser(to topic: String, title: String, body: String) {
        
            let urlString = "https://fcm.googleapis.com/v1/projects/myprojectnamehere-41f12/messages:send HTTP/1.1"
            guard let encodedURLString = urlString.addingPercentEncoding(withAllowedCharacters: .urlFragmentAllowed) else { return }
            let url = URL(string: encodedURLString)!
            let paramString: [String: Any] = [
                                               "message": [
                                                "topic" : topic,
                                                "notification" : [
                                                    "title": title,
                                                    "body": body
                                                ]
                                              ]
                                            ]
            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("Bearer ya29.\(self.bearer)", forHTTPHeaderField: "Authorization")
            let task = URLSession.shared.dataTask(with: request as URLRequest) { (data, response, error) in
                do {
                    if let jsonData = data {
                        if let jsonDataDictionary = try JSONSerialization.jsonObject(with: jsonData, options: JSONSerialization.ReadingOptions.allowFragments) as? [String: AnyObject] {
                            NSLog("Received data:\n\(jsonDataDictionary))")
                        }
                    }
                } catch let err as NSError {
                    print(err)
                }
            }
            task.resume()
        
    
}

So looking back I had to revamp my function above and change the parameters a bit, but now when the function is called...

getTheSchoolID { (id) in
            if let id = id {
                self.sendNotificationToUser(to: id, title: "New Event Added!", body: "A new event has been added to the dashboard!!")

            }
        }

I get this error in the debug console:

error

I wanted it to basically equal to this code snippet in the Firebase docs: json topics

So I decided to head over to jsonlint.com and validate it. I replaced the square brackets with curly brackets, put double-quotes on id, body, and title, and the json was perfectly valid, but when I run it in Swift, it says it's invalid. The id, body, and title in my HTTP request are all String format, and I used two out of those 3 variables in the first json data I posted above and it worked perfectly fine, so I can't figure out why the console isn't picking up on the JSON. If anyone can help me figure this out, that would be awesome. Thank you.

0

There are 0 best solutions below