Search code examples
iosgraphqlapolloapollo-client

How to add header in Apollo GraphQL : iOS


Hy I am working in a project with Apollo GraphQL method and its working fine. But now the client required for adding additional header with Apollo API's. But after adding the header the API's response return as unAuthorized.

I am adding the header as,

    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))

    }()

Anyone please help me to find out how to add headers with Apollo GraphQL.


Solution

  • Finally I found the answer. Add the header in the following way,

     let apolloAuth: ApolloClient = {
            let configuration = URLSessionConfiguration.default
    
            let token = UserDefaults.standard.value(forKey: "token")
            // Add additional headers as needed
            configuration.httpAdditionalHeaders = ["authorization":"\(token!)", "channel":"mobile"]
            let url = URL(string: "http://xxxx/graphql")!
    
            return ApolloClient(networkTransport: HTTPNetworkTransport(url: url, configuration: configuration))
    
        }()
    

    Hope it will help someone.