Apollo GraphQL标头在iOS Swift中总是会失败 [英] Apollo GraphQL header always gives failure in iOS Swift

查看:211
本文介绍了Apollo GraphQL标头在iOS Swift中总是会失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的swift项目中,我第一次使用Apollo GraphQL客户端.遵循他们文档中提到的所有步骤,并在Google上搜索了我的问题,但是没有运气.我通过在请求URL中传递标头来发出查询请求,但它总是使我失败,并显示错误消息,例如 failure(Apollo.LegacyParsingInterceptor.LegacyParsingError.couldNotParseToLegacyJSON(data:1839 bytes)).我已提及链接的答案,但这不适用于我.任何帮助将不胜感激.

I am working with the Apollo GraphQL client for the first time in my swift project. Followed all the steps mentioned in their document and searched over google for my issue but had no luck. I have made a query request by passing a header in my request URL but it always gives me a failure with error msg like failure(Apollo.LegacyParsingInterceptor.LegacyParsingError.couldNotParseToLegacyJSON(data: 1839 bytes)). I have referred answer of link but this is not worked for me. Any Help will be most appreciated.

导入UIKit

导入阿波罗

class Network {

static let shared = Network()

private(set) lazy var apollo: ApolloClient = {

    let cache = InMemoryNormalizedCache()
    let store1 = ApolloStore(cache: cache)
    let client1 = URLSessionClient()
    let provider = NetworkInterceptorProvider(store: store1, client: client1)
    
    let url = URL(string:"https://Storename.myshopify.com/admin/api/2021-04/graphql")!
    
    let requestChainTransport = RequestChainNetworkTransport(interceptorProvider: provider,endpointURL: url)
    
    return ApolloClient(networkTransport: requestChainTransport,
                        store: store1)
}()}


class RequestOrderDetailInterceptor: ApolloInterceptor {

func interceptAsync<Operation: GraphQLOperation>(
    chain: RequestChain,
    request: HTTPRequest<Operation>,
    response: HTTPResponse<Operation>?,
    completion: @escaping (Result<GraphQLResult<Operation.Data>, Error>) -> Void) {
    
    request.addHeader(name: "X-Shopify-Access-Token", value: "MyToken")
    print( "Outgoing request: \(request)")
    chain.proceedAsync(request: request,
                       response: response,
                       completion: completion)
}

}

class ResponseOrderDetailInterceptor: ApolloInterceptor {

enum ResponseLoggingError: Error {
    case notYetReceived
}

func interceptAsync<Operation: GraphQLOperation>(
    chain: RequestChain,
    request: HTTPRequest<Operation>,
    response: HTTPResponse<Operation>?,
    completion: @escaping (Result<GraphQLResult<Operation.Data>, Error>) -> Void) {

    request.addHeader(name: "X-Shopify-Access-Token", value: "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")

    defer {

        chain.proceedAsync(request: request,
                           response: response,
                           completion: completion)

    }

    guard let receivedResponse = response else {
        chain.handleErrorAsync(ResponseLoggingError.notYetReceived,
                               request: request,
                               response: response,
                               completion: completion)
        return

    }

        print("HTTP Response: \(receivedResponse.httpResponse)")

    if let stringData = String(bytes: receivedResponse.rawData, encoding: .utf8) {
        print("Data: \(stringData)")
    } else {
        print("Could not convert data to string!")
    }
}

}

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(),
        LegacyCacheReadInterceptor(store: self.store),
        RequestOrderDetailInterceptor(),
        NetworkFetchInterceptor(client: self.client),
        ResponseOrderDetailInterceptor(),
        ResponseCodeInterceptor(),
        LegacyParsingInterceptor(cacheKeyForObject: self.store.cacheKeyForObject),
        AutomaticPersistedQueryInterceptor(),
        LegacyCacheWriteInterceptor(store: self.store)
    ]
}

}

///这里我正在使用我的apollo客户端来获取记录

//Here I am using my apollo client to fetch records

 func getOrderDetails(){

 Network.shared.apollo.fetch(query: OrderDetailsByIdQuery(id: GraphQL.ID(rawValue: "Z2lkOi8vc2hvcGlmeS9PcmRlci8zNzcxODAxNjk4NDY5P2tleT1kNGRiMmVhODFlNGVlNzg1NzhhMDQ4ODI2Mzc4ZTkxMw==").rawValue))  {  result in

        print(result) 

        switch result {

        case .success(let graphQLResult):
           
                print("Oreder Details:",graphQLResult.data?)
            
        case .failure(let error):
            print("Error loading data \(error.localizedDescription)")
        }
    }

}

推荐答案

我看到您最近对别人的问题发表评论,只是想知道您是否取得了成功?这是我找到您的评论的问题.

I saw your recent comment on someone else's issue and just wondering if you've had any success? Here's the issue where I found your comment.

如何在Apollo GraphQL中添加标题:iOS

这篇关于Apollo GraphQL标头在iOS Swift中总是会失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆