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

标签 ios graphql apollo apollo-client

我正在与 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/

相关文章:

javascript - 需要相机叠加(半透明)图片HowTo

iOS:将不可编辑的字符串附加到 UITextView 的末尾

mongodb - 看不到关系 - Loopback 4 + MongoDB + openapi-to-graphql

branch - 如何使用 GraphQL 获取 GitHub 分支名称

ruby-on-rails - Rails Graphql 解决错误 : wrong number of arguments (given 1, 预期 3)

reactjs - 如何在 Apollo/GraphQL 和 React 中使用状态和 useQuery?

iphone - 滚动时调整 UICollectionView 的大小

ios - 针对 iPhone 3.5 英寸屏幕优化我的应用

apollo - `data` 在 apollo useMutation Promise 中未定义

java - 在 GraphQL (Apollo) 中转换 InputType 对象