Import these two elements
import UIKit
import Apollo
Create a class Network and paste below source code
struct Network {
static var request = 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: "http://xxx/graphql")!
let requestChainTransport = RequestChainNetworkTransport(interceptorProvider: provider,
endpointURL: url)
return ApolloClient(networkTransport: requestChainTransport,
store: store1)
}()
}
add NetworkInterceptorProvider in Network class
class NetworkInterceptorProvider: LegacyInterceptorProvider {
override func interceptors<Operation: GraphQLOperation>(for operation: Operation) -> [ApolloInterceptor] {
var interceptors = super.interceptors(for: operation)
interceptors.insert(CustomInterceptor(), at: 0)
return interceptors
}
}
add CustomInterceptor also in Network class
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)
}
}
finally call this method from ViewController
func todoQueryCloud(){
Network.request.apollo.fetch(query: ProgressionsQuery()){result in
// 3
switch result {
case .success(let graphQLResult):
guard let data = try? result.get().data else { return }
if graphQLResult.data != nil {
// 4
print("Loaded data \(String(describing: data.progressions))")
self.collectionView.reloadData()
}
case .failure(let error):
// 5
print("Error loading data \(error)")
}
}
}