首页 > 解决方案 > apollo-ios 如何在磁盘上缓存数据?

问题描述

我需要将我的数据缓存在磁盘上以供离线查看,我在 apollo-ios 源中找到了 ApolloSQLite,但我找不到 ApolloSQLite 的任何文档(我也尝试过 Google 搜索)。

环境:

Xcode 10.1
macOS 10.14.3
CocoaPods 1.5.3

Apollo (0.9.5)
SQLite.swift (0.11.5)

之后出现太多错误pod install

pod 'Apollo'
pod 'Apollo/SQLite'

在此处输入图像描述

标签: iosswiftgraphqlapollo-ios

解决方案


当我使用时,在之后CocoaPods 1.5.3缺少源,会导致错误。我已经通过将 CocoaPods 升级到 1.6.0 来修复它。Apollo/Corepod install

顺便说一句,最初的问题是如何使用 ApolloSQLite?因为我没有找到任何关于 ApolloSQLite 的文档。经过太多的搜索和查询,我将我的步骤列出如下,以寻求其他人的帮助:

  1. 使用 CocoaPods 管理库:
pod 'Apollo'
pod 'Apollo/SQLite'
  1. 需要一个文件路径来保存用于缓存数据的 sqlite 文件。粘贴我的代码以供参考:

    func temporarySQLiteFileURL() -> URL {
        let applicationSupportPath = NSSearchPathForDirectoriesInDomains(.applicationSupportDirectory, .userDomainMask, true).first!
        let dbPath = applicationSupportPath + "/com.[special name].cache"
    
        if !FileManager.default.fileExists(atPath: dbPath) {
            try? FileManager.default.createDirectory(atPath: dbPath, withIntermediateDirectories: true, attributes: nil)
        }
    
        let url = URL(fileURLWithPath: dbPath)
        return url.appendingPathComponent("db.sqlite3")
    }
    
  2. 配置 ApolloClient:

        let configuration = URLSessionConfiguration.default
        configuration.timeoutIntervalForRequest = 10
    
        let url = URL(string: self.graphQLApiAddress!)!
        let networkTransport = HTTPNetworkTransport(url: url, configuration: configuration)
    
        let cache = try? SQLiteNormalizedCache(fileURL: temporarySQLiteFileURL())
        let store = ApolloStore(cache: cache ?? InMemoryNormalizedCache())
        self.apolloClient = ApolloClient(networkTransport: networkTransport, store: store)
    

推荐阅读