gpt4 book ai didi

ios - 如何调用 graphql API

转载 作者:行者123 更新时间:2023-11-28 19:26:44 25 4
gpt4 key购买 nike

如何在 View Controller 中调用 graphql API。我正在调用如下结构的 API

let url = URL(string: "http://xxxx.com/graphql")!

var request = URLRequest(url: url)
request.httpMethod = "POST"

let query = "{query:mutation {\n signin(email: \"adc.inlove@gmail.com\", password: \"qwerty\") {\n result {\n token\n firstName\n lastName\n profileImage\n status\n }\n }\n}\n}"
let body = ["query": query]
request.httpBody = try! JSONSerialization.data(withJSONObject: body, options: [])
request.cachePolicy = .reloadIgnoringLocalCacheData

let task = URLSession.shared.dataTask(with: request, completionHandler: { data, _, error in
if let error = error { print(error); return }
guard let data = data else { print("Data is missing."); return }
do {
let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments)
print(json)
} catch let e {
print("Parse error: \(e)")
}
})
task.resume()`

但它显示错误为,

Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0." UserInfo={NSDebugDescription=Invalid value around character 0.}

而且它在 postman 和获取输出中也能完美运行。任何人都请帮助我找出解决方案。

最佳答案

这是您当前发送的文档:

{
query:mutation {
signin(email: "adc.inlove@gmail.com", password: "qwerty") {
result {
token
firstName
lastName
profileImage
status
}
}
}
}

这不是 GraphQL 文档的正确语法。根据规范,文档应具有以下格式:

OperationType [Name] [VariableDefinitions] [Directives] SelectionSet

其中括号表示可选元素,操作类型是querymutationsubscription之一,选择集是一个或多个字段包裹在一组大括号中。

如果省略操作类型,则文档被假定为查询。这被称为“查询速记”。所以给出一个有效的查询,如:

query SomeOperationName {
users {
name
}
}

下面是等价的:

{
users {
name
}
}

不过,以上仅适用于查询,不适用于突变。综上所述,您的文档有一组额外的大括号和无效的操作类型。至少,将其更改为:

mutation {
signin (email: "adc.inlove@gmail.com", password: "qwerty") {
result {
token
firstName
lastName
profileImage
status
}
}
}

或者...

let query = "mutation { signin(email: \"adc.inlove@gmail.com\", password: \"qwerty\") { result { token firstName lastName profileImage status } } }"

关于ios - 如何调用 graphql API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53168292/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com