Calling Cloud Function from Swift with JSON data

混江龙づ霸主 提交于 2021-01-28 05:20:49

问题


I have a Cloud Function hosted on Firebase that I am trying to call from a Swift app. It works fine when I call it from command line with the following script, however there is some issue with parsing the JSON data when I call it from swift.

Command Line (works perfectly)

time curl -v -X POST -d '{"url":"https://cdn.bmstores.co.uk/images/hpcProductImage/imgFull/303441-Volvic-6x500ml-Naural-Mineral-Water1.jpg"}' -H "Content-type: application/json" https://us-central1-themagicfactory-5cf7a.cloudfunctions.net/fastMatches

Swift Code (doesn't work)

functions.httpsCallable("fastMatches").call("{\"url\":\"https://cdn.bmstores.co.uk/images/hpcProductImage/imgFull/303441-Volvic-6x500ml-Naural-Mineral-Water1.jpg\"}", completion: {(result,error) in
    if let error = error{
        print("An error occurred while calling the test function: \(error)" )
    }
    print("Results from test cloud function: \(result)")
})

Python Pseudo (cloud function)

def fastMatches(request):
    print(request)
    req = urllib.request.urlopen(request.json["url"])

Request being weird when called from Swift

EDIT: I get the same weird results even if I call it from a manual HTTPs request.

let json: [String: String] = ["url": "https://cdn.bmstores.co.uk/images/hpcProductImage/imgFull/303441-Volvic-6x500ml-Naural-Mineral-Water1.jpg"]

let jsonData = try? JSONSerialization.data(withJSONObject: json)

// create post request
let url = URL(string: "https://us-central1-themagicfactory-5cf7a.cloudfunctions.net/fastMatches")!
var request = URLRequest(url: url)
request.httpMethod = "POST"

// insert json data to the request
request.httpBody = jsonData

let task = URLSession.shared.dataTask(with: request) { data, response, error in
    print(data,response,error)
    guard let data = data, error == nil else {
        print(error?.localizedDescription ?? "No data")
        return
    }
    let responseJSON = try? JSONSerialization.jsonObject(with: data, options: [])
    if let responseJSON = responseJSON as? [String: Any] {
        print(responseJSON)
    }
}

task.resume()

来源:https://stackoverflow.com/questions/56491071/calling-cloud-function-from-swift-with-json-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!