【问题标题】:How to add header in Apollo GraphQL 0.49.1 for iOS如何在 Apollo GraphQL 0.49.1 for iOS 中添加标题
【发布时间】:2021-12-15 14:36:35
【问题描述】:
我正在使用这段代码,但这段代码给了我类似的错误
- 在范围内找不到“HTTPNetworkTransport”
- 在范围内找不到类型“HTTPNetworkTransportDelegate”
final class Network {
static let shared = Network()
private lazy var networkTransport: NetworkTransport = {
let transport = HTTPNetworkTransport(url: URL(string: "https://exampe.com/grapghql")!)
transport.delegate = self
return transport
}()
private(set) lazy var apollo = ApolloClient(networkTransport: self.networkTransport)
}
extension Network: HTTPNetworkTransportDelegate {
func networkTransport(_ networkTransport: NetworkTransport, shouldSend request: URLRequest) -> Bool {
return true
}
func networkTransport(_ networkTransport: NetworkTransport, willSend request: inout URLRequest) {
let token = ""
var headers = request.allHTTPHeaderFields ?? [String: String]()
headers["Authorization"] = "Bearer \(token)"
request.allHTTPHeaderFields = headers
}
}
【问题讨论】:
标签:
ios
swift
graphql
apollo
【解决方案1】:
我认为这段代码肯定对你有帮助。
您可以通过这种方式创建您的客户端。
import Foundation
import Apollo
class Network {
static let shared = Network()
var apollo: ApolloClient {
// The cache is necessary to set up the store, which we're going to hand to the provider
let cache = InMemoryNormalizedCache()
let store = ApolloStore(cache: cache)
let accessToken = "SET_AUTHORIZATION_TOKEN" // TODO: - "Authorization_TOKEN"
let authPayloads = ["Authorization": "Bearer \(String(describing: accessToken))"]
let configuration = URLSessionConfiguration.default
configuration.httpAdditionalHeaders = authPayloads
configuration.requestCachePolicy = .reloadIgnoringLocalCacheData
let client = URLSessionClient(sessionConfiguration: configuration, callbackQueue: nil)
let provider = NetworkInterceptorProvider(store: store, client: client)
let endpointURL = URL(string: "YOUR_ENDPOINT_URL")!// TODO: - "YOUR_ENDPOINT_URL"
let requestChainTransport = RequestChainNetworkTransport(interceptorProvider: provider, endpointURL: endpointURL)
// Remember to give the store you already created to the client so it
// doesn't create one on its own
return ApolloClient(networkTransport: requestChainTransport, store: store)
}
}
struct NetworkInterceptorProvider: InterceptorProvider {
// These properties will remain the same throughout the life of the `InterceptorProvider`, even though they
// will be handed to different interceptors.
private let store: ApolloStore
private let client: URLSessionClient
init(store: ApolloStore,
client: URLSessionClient) {
self.store = store
self.client = client
}
func interceptors<Operation: GraphQLOperation>(for operation: Operation) -> [ApolloInterceptor] {
return [
MaxRetryInterceptor(),
CacheReadInterceptor(store: self.store),
NetworkFetchInterceptor(client: self.client),
ResponseCodeInterceptor(),
JSONResponseParsingInterceptor(cacheKeyForObject: self.store.cacheKeyForObject),
AutomaticPersistedQueryInterceptor(),
CacheWriteInterceptor(store: self.store)
]
}
}