7

When I try to run a Firebase Function from Swift, I get an error saying:

Error Domain=NSCocoaErrorDomain Code=3840 "JSON text did not start with array or object and option to allow fragments not set." UserInfo={NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}

This is the Firebase Function:

exports.helloWorld = functions.https.onRequest((request, response) => {
  response.send("Hello from Firebase!")
})

This is my Swift code:

Functions.functions().httpsCallable("helloWorld").call { (result, error) in
  if error == nil {
    print("Success: \(result?.data)")
  } else {
    print(error.debugDescription)
  }
}
Lunke
  • 151
  • 7
  • The error message *"JSON text did not start..."* means what it says. Make a string from the affected data, print it and check it out. – vadian Jul 05 '18 at 07:58
  • The 'result' variable is nil though... – Lunke Jul 05 '18 at 08:04
  • Maybe the data to be sent must have a specific (JSON) format. – vadian Jul 05 '18 at 08:07
  • There's a difference between callable Cloud Functions and request cloud functions. See [this question](https://stackoverflow.com/questions/51159634/firebase-https-callable-ios-swift/51159789#51159789) and then refer to [Call Functions via HTTP Requests](https://firebase.google.com/docs/functions/http-events) for some details as I think your wanting onCall not onRequest, then again maybe not but it's good info either way. – Jay Jul 08 '18 at 13:48
  • @Lunke any update on this? I've run into the same problem. – Zoltán Matók Apr 12 '19 at 19:00

3 Answers3

9

You may see this error if you haven't specified the correct region on the client side. For example:

lazy var functions = Functions.functions(region: "europe-west1")
SteffenK
  • 582
  • 6
  • 17
  • 1
    This was so helpful! Simple solution to a misleading error message! – Sunkas Nov 03 '21 at 13:35
  • Wow. Hours and hours. Missed `Note: To call a function running in any location other than the default us-central1, you must set the appropriate value at initialization. ` at https://firebase.google.com/docs/functions/callable – user Dec 16 '22 at 03:30
1

My issue was that I used http://localhost:5000 instead of the correct http://localhost:5001. The emulator by default emulates the hosted website at port 5000 and the functions at port 5001.

I realized this by evaluating the response in FIRFunctions.m#261. It was the html of the hosted website which obviously cannot be parsed as json.

Simon Bengtsson
  • 7,573
  • 3
  • 58
  • 87
0

response.send("Hello from Firebase!")

You are not returning a JSON TEXT here but you are returning a string.

You need to return something like

response.send('{"message": "Hello from Firebase!"}')

Muvimotv
  • 853
  • 9
  • 14