swift - 尝试使用 Alamofire 缓存但没有结果

标签 swift caching alamofire

我正在尝试使用 Alamofire 缓存,所以我想要的行为是第一次从网络加载,下次如果数据存在于缓存中则返回它而不发出更多请求......在我考虑过期之后...

我的代码总是返回响应 nil...对此有什么建议吗?谢谢

    let config = NSURLSessionConfiguration.defaultSessionConfiguration()
    config.URLCache = NSURLCache.sharedURLCache()
    config.requestCachePolicy = NSURLRequestCachePolicy.ReturnCacheDataElseLoad
    let manager = Alamofire.Manager(configuration: config)
    manager.request(.GET, url, parameters: parameters, encoding: .URL, headers: ["Token":LocalStorage.read("token") as! String, "Version":"2"]).responseJSON { (response) in

        if let json = response.result.value
        {
            if response.response?.statusCode == 200
            {
                completionHandler(parser.parseSwifty(JSON(json)), nil)
            }
            else
            {
                completionHandler(nil, serverErrorMessage)
            }
        }
        else
        {
            completionHandler(nil, networkErrorMessage)
        }

    }

最佳答案

所以...我解决了这个问题: 在我的 NetworkHelper 中,我添加了一个计算属性,如下所示:

    static let manager: Manager = {
    let memoryCapacity = 100 * 1024 * 1024; // 100 MB
    let diskCapacity = 100 * 1024 * 1024; // 100 MB
    let cache = NSURLCache(memoryCapacity: memoryCapacity, diskCapacity: diskCapacity, diskPath: "shared_cache")

    let configuration: NSURLSessionConfiguration = NSURLSessionConfiguration.defaultSessionConfiguration()
    configuration.HTTPAdditionalHeaders = ["Token":LocalStorage.read("token") as! String, "Version":"2"]
    configuration.requestCachePolicy = .ReturnCacheDataElseLoad // this is the default
    configuration.URLCache = cache

    return Manager(configuration: configuration)
}()

当我必须检索一些数据时:

        self.manager.request(.GET, url, parameters: parameters, encoding: .URL)
        .response { (request, response, data, error) in
            debugPrint(request)
            debugPrint(response)
            debugPrint(error)
    }.responseJSON......

我还编写了一个函数来预加载一些数据,如下所示:

    static func preloadGetRequest(url : String, parameters: Dictionary<String, String>?)
{
    self.manager.request(.GET, url, parameters: parameters, encoding: .URL)
        .response { (request, response, data, error) in
            debugPrint(request)
            debugPrint(response)
            debugPrint(error)
    }
}

试着让我知道:)

关于swift - 尝试使用 Alamofire 缓存但没有结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39780553/

相关文章:

ios - 如何将二维数组填充到 CollectionView 上?

php - 使用 PHP/Apache 缓存操作码的最简单方法是什么?

ios - Swift 中带有 Firestore 的完成处理程序的替代方案

javascript - WKWebView 在加载任何 URL 时阻止某些脚本(阻止任何网站中的跟踪或广告)

c - 如果预取无效地址会怎样?

python - 如何使用 python django 清除浏览器缓存?

swift - 为什么上传 alamofire 后台请求不在后台执行?

ios - 如何在调用 AlamoFire 的 POST 函数时使用完成处理程序?

ios - 使用 Alamofire 将文件上传到 amazon s3

Swift:在 View Controller 内的 UILabel 中使用 Int