gpt4 book ai didi

ios - 如何在 Apollo GraphQL : iOS 中添加 header

转载 作者:行者123 更新时间:2023-12-04 13:20:59 26 4
gpt4 key购买 nike

我正在与 Apollo GraphQL 合作的项目中工作。方法及其工作正常。但现在客户端需要使用 Apollo API 添加额外的 header 。但在添加 header 后,API 的响应返回为未授权。

我将标题添加为,

    let apolloAuth: ApolloClient = {
let configuration = URLSessionConfiguration.default

// Add additional headers as needed
configuration.httpAdditionalHeaders = ["Authorization" : self.singleTonInstance.token]
configuration.httpAdditionalHeaders = ["channel" : "mobile"]

let url = URL(string: "http://xxx/graphql")!

return ApolloClient(networkTransport: HTTPNetworkTransport(url: url, configuration: configuration))

}()

请任何人帮助我了解如何使用 Apollo GraphQL 添加标题。

最佳答案

更新:“Apollo Client v0.41.0”和“Swift 5”的解决方案
我在使用 Apollo Client v0.41.0 和 Swift 5.0 时遇到了同样的问题,但上述解决方案都没有奏效。经过数小时的试用后终于能够找到解决方案。以下解决方案使用 Apollo Client v0.41.0 和 Swift 5 进行了测试

import Foundation
import Apollo

class Network {
static let shared = Network()

private(set) lazy var apollo: ApolloClient = {

let cache = InMemoryNormalizedCache()
let store1 = ApolloStore(cache: cache)
let authPayloads = ["Authorization": "Bearer <<TOKEN>>"]
let configuration = URLSessionConfiguration.default
configuration.httpAdditionalHeaders = authPayloads

let client1 = URLSessionClient(sessionConfiguration: configuration, callbackQueue: nil)
let provider = NetworkInterceptorProvider(client: client1, shouldInvalidateClientOnDeinit: true, store: store1)

let url = URL(string: "https://<HOST NAME>/graphql")!

let requestChainTransport = RequestChainNetworkTransport(interceptorProvider: provider,
endpointURL: url)

return ApolloClient(networkTransport: requestChainTransport,
store: store1)
}()
}
class NetworkInterceptorProvider: DefaultInterceptorProvider {
override func interceptors<Operation: GraphQLOperation>(for operation: Operation) -> [ApolloInterceptor] {
var interceptors = super.interceptors(for: operation)
interceptors.insert(CustomInterceptor(), at: 0)
return interceptors
}
}

class CustomInterceptor: ApolloInterceptor {

func interceptAsync<Operation: GraphQLOperation>(
chain: RequestChain,
request: HTTPRequest<Operation>,
response: HTTPResponse<Operation>?,
completion: @escaping (Swift.Result<GraphQLResult<Operation.Data>, Error>) -> Void) {
request.addHeader(name: "Authorization", value: "Bearer <<TOKEN>>")

print("request :\(request)")
print("response :\(String(describing: response))")

chain.proceedAsync(request: request,
response: response,
completion: completion)
}
}

关于ios - 如何在 Apollo GraphQL : iOS 中添加 header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55395589/

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