【问题标题】:SwiftUI :how to add authentication header in apollo graphQl(iOS) with swift?SwiftUI:如何使用 swift 在 apollo graphQl(iOS) 中添加身份验证标头?
【发布时间】:2020-07-05 20:48:29
【问题描述】:
在 apollo graphQl(iOS) 中通过身份验证标头的任何解决方案
我不知道如何通过请求的 url 传递标头。
我试过这样:
import Apollo
class Network {
static let shared = Network()
let accessToken = "token-KEY"
private(set) lazy var apollo = ApolloClient(url: URL(string: "http://localhost:1337/graphql")!)
}
有人帮我吗?
【问题讨论】:
标签:
ios
xcode
graphql
apollo
【解决方案1】:
class Network {
static let shared = Network()
private(set) lazy var apollo: ApolloClient = {
let client = URLSessionClient()
let cache = InMemoryNormalizedCache()
let store = ApolloStore(cache: cache)
let provider = NetworkInterceptorProvider(client: client, store: store)
let url = URL(string: ENDPOINT_URL)!
let transport = RequestChainNetworkTransport(interceptorProvider: provider,
endpointURL: url)
return ApolloClient(networkTransport: transport)
}()
}
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
}
}
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: TOKEN_VALUE)
print("request :\(request)")
print("response :\(String(describing: response))")
chain.proceedAsync(request: request,
response: response,
completion: completion)
}
}