如何使用Alamofire运行结构化查询?

发布于 2025-01-31 16:39:19 字数 2820 浏览 4 评论 0原文

如下图所示,它在Postman中效果很好。

postman

但是,我的代码不起作用...

func getMy() {
    let projectId = "lolcourt-554c8"
    let url = "https://firestore.googleapis.com/v1/projects/\(projectId)/databases/(default)/documents:runQuery"
    var request = URLRequest(url: URL(string: url)!)
    request.httpMethod = "POST"
    do {
        let post = MyPost(userId: "Mr.Kim")
        request.httpBody = try JSONEncoder().encode(post)
    } catch {
        print("http Body Error")
    }
    AF.request(request).responseString { response in
        print(response)
    }

输出:

success("[{\n  \"error\": {\n    \"code\": 400,\n    \"message\": \"Invalid JSON payload received. Unknown name \\\"{\\\"structuredQuery\\\":{\\\"where\\\":{\\\"fieldFilter\\\":{\\\"field\\\":{\\\"fieldPath\\\":\\\"userID\\\"},\\\"op\\\":\\\"EQUAL\\\",\\\"value\\\":{\\\"stringValue\\\":\\\"Mr.Kim\\\"}}},\\\"orderBy\\\":[{\\\"field\\\":{\\\"fieldPath\\\":\\\"date\\\"},\\\"direction\\\":\\\"DESCENDING\\\"}],\\\"from\\\":[{\\\"collectionId\\\":\\\"lolCourt\\\"}]}}\\\": Cannot bind query parameter. Field \'{\\\"structuredQuery\\\":{\\\"where\\\":{\\\"fieldFilter\\\":{\\\"field\\\":{\\\"fieldPath\\\":\\\"userID\\\"},\\\"op\\\":\\\"EQUAL\\\",\\\"value\\\":{\\\"stringValue\\\":\\\"Mr\' could not be found in request message.\",\n    \"status\": \"INVALID_ARGUMENT\",\n    \"details\": [\n      {\n        \"@type\": \"type.googleapis.com/google.rpc.BadRequest\",\n        \"fieldViolations\": [\n          {\n            \"description\": \"Invalid JSON payload received. Unknown name \\\"{\\\"structuredQuery\\\":{\\\"where\\\":{\\\"fieldFilter\\\":{\\\"field\\\":{\\\"fieldPath\\\":\\\"userID\\\"},\\\"op\\\":\\\"EQUAL\\\",\\\"value\\\":{\\\"stringValue\\\":\\\"Mr.Kim\\\"}}},\\\"orderBy\\\":[{\\\"field\\\":{\\\"fieldPath\\\":\\\"date\\\"},\\\"direction\\\":\\\"DESCENDING\\\"}],\\\"from\\\":[{\\\"collectionId\\\":\\\"lolCourt\\\"}]}}\\\": Cannot bind query parameter. Field \'{\\\"structuredQuery\\\":{\\\"where\\\":{\\\"fieldFilter\\\":{\\\"field\\\":{\\\"fieldPath\\\":\\\"userID\\\"},\\\"op\\\":\\\"EQUAL\\\",\\\"value\\\":{\\\"stringValue\\\":\\\"Mr\' could not be found in request message.\"\n          }\n        ]\n      }\n    ]\n  }\n}\n]")

我认为编码完成了没有任何错误。

if let encoded = try? JSONEncoder().encode(MyPost(userId: "Mr.Kim")) {
        print(String(data: encoded, encoding: .utf8)!)
    }

输出:

{"structuredQuery":{"where":{"fieldFilter":{"field":{"fieldPath":"userID"},"op":"EQUAL","value":{"stringValue":"Mr.Kim"}}},"orderBy":[{"field":{"fieldPath":"date"},"direction":"DESCENDING"}],"from":[{"collectionId":"lolCourt"}]}}

As you can see in the image below, It works well in PostMan.

PostMan

But, my code didn't work...

func getMy() {
    let projectId = "lolcourt-554c8"
    let url = "https://firestore.googleapis.com/v1/projects/\(projectId)/databases/(default)/documents:runQuery"
    var request = URLRequest(url: URL(string: url)!)
    request.httpMethod = "POST"
    do {
        let post = MyPost(userId: "Mr.Kim")
        request.httpBody = try JSONEncoder().encode(post)
    } catch {
        print("http Body Error")
    }
    AF.request(request).responseString { response in
        print(response)
    }

Output:

success("[{\n  \"error\": {\n    \"code\": 400,\n    \"message\": \"Invalid JSON payload received. Unknown name \\\"{\\\"structuredQuery\\\":{\\\"where\\\":{\\\"fieldFilter\\\":{\\\"field\\\":{\\\"fieldPath\\\":\\\"userID\\\"},\\\"op\\\":\\\"EQUAL\\\",\\\"value\\\":{\\\"stringValue\\\":\\\"Mr.Kim\\\"}}},\\\"orderBy\\\":[{\\\"field\\\":{\\\"fieldPath\\\":\\\"date\\\"},\\\"direction\\\":\\\"DESCENDING\\\"}],\\\"from\\\":[{\\\"collectionId\\\":\\\"lolCourt\\\"}]}}\\\": Cannot bind query parameter. Field \'{\\\"structuredQuery\\\":{\\\"where\\\":{\\\"fieldFilter\\\":{\\\"field\\\":{\\\"fieldPath\\\":\\\"userID\\\"},\\\"op\\\":\\\"EQUAL\\\",\\\"value\\\":{\\\"stringValue\\\":\\\"Mr\' could not be found in request message.\",\n    \"status\": \"INVALID_ARGUMENT\",\n    \"details\": [\n      {\n        \"@type\": \"type.googleapis.com/google.rpc.BadRequest\",\n        \"fieldViolations\": [\n          {\n            \"description\": \"Invalid JSON payload received. Unknown name \\\"{\\\"structuredQuery\\\":{\\\"where\\\":{\\\"fieldFilter\\\":{\\\"field\\\":{\\\"fieldPath\\\":\\\"userID\\\"},\\\"op\\\":\\\"EQUAL\\\",\\\"value\\\":{\\\"stringValue\\\":\\\"Mr.Kim\\\"}}},\\\"orderBy\\\":[{\\\"field\\\":{\\\"fieldPath\\\":\\\"date\\\"},\\\"direction\\\":\\\"DESCENDING\\\"}],\\\"from\\\":[{\\\"collectionId\\\":\\\"lolCourt\\\"}]}}\\\": Cannot bind query parameter. Field \'{\\\"structuredQuery\\\":{\\\"where\\\":{\\\"fieldFilter\\\":{\\\"field\\\":{\\\"fieldPath\\\":\\\"userID\\\"},\\\"op\\\":\\\"EQUAL\\\",\\\"value\\\":{\\\"stringValue\\\":\\\"Mr\' could not be found in request message.\"\n          }\n        ]\n      }\n    ]\n  }\n}\n]")

I think the encoding was completed without any errors.

if let encoded = try? JSONEncoder().encode(MyPost(userId: "Mr.Kim")) {
        print(String(data: encoded, encoding: .utf8)!)
    }

Output:

{"structuredQuery":{"where":{"fieldFilter":{"field":{"fieldPath":"userID"},"op":"EQUAL","value":{"stringValue":"Mr.Kim"}}},"orderBy":[{"field":{"fieldPath":"date"},"direction":"DESCENDING"}],"from":[{"collectionId":"lolCourt"}]}}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

万劫不复 2025-02-07 16:39:19

这与参数编码有关,只需添加此标头

request.addValue("application/json", forHTTPHeaderField: "Content-Type")

This related to parameter encoding , simply add this header

request.addValue("application/json", forHTTPHeaderField: "Content-Type")
何处潇湘 2025-02-07 16:39:19

无需您自己的参数编码,Alamofire具有内置。

AF.request(url: ..., method: .post, parameters: post, encoder: JSONParameterEncoder.default)

这将正确编码任何编码键入JSON。

PS。要打印响应json而不逃脱,我建议print(字符串(Decoding:data,as:utf8.self)为NSString)

There's no need to do you own parameter encoding, Alamofire has that built in.

AF.request(url: ..., method: .post, parameters: post, encoder: JSONParameterEncoder.default)

This will properly encode any Encodable type as JSON.

PS. To print response JSON without escaping I recommend print(String(decoding: data, as: UTF8.self) as NSString)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文