如何在iOS中缓存响应并仅在互联网不可用时显示?

Lio*_*ion 1 caching ios swift alamofire urlsession

我想缓存API的响应。当互联网可用时,它应该从服务器获取数据,并且每次都应该更新本地缓存的数据,当互联网不可用时,它应该显示缓存的数据。有可能吗Alamofire or URLSession?或者我是否需要使用数据库并且我应该手动处理这个问题?

Sha*_*ank 6

如果你使用这样的方法怎么办URLRequest

var urlRequest = URLRequest(url: url)
// Configure your URLRequest as you wish with headers etc

// Load from the cache
urlRequest.cachePolicy = .returnCacheDataDontLoad

// Load from the source
if networkStatus == available {
    urlRequest.cachePolicy = .reloadIgnoringLocalCacheData
}

let task = URLSession.shared.dataTask(with: urlRequest) { [weak self] data, response, error in

   // You will get data from the source when internet is available
   // You will get data from your cache when internet isn't available
   if let data = data {
      // Reload your UI with new or cached data
   }

   // There is some error in your request or server
   // Or the internet isn't available and the cache is empty
   if let error = error {
      // Update your UI to show an error accordingly
   }

}

task.resume()
Run Code Online (Sandbox Code Playgroud)

根据 OP 评论进行更新

我第一次打开应用程序,并且有互联网并且从服务器加载数据。现在我正在关闭互联网并打开应用程序,但不会显示数据,因为由于 reloadIgnoringLocalCacheData 此策略,当互联网存在时,它没有将数据存储在缓存中。此策略不在缓存中存储数据。

设置为cachePolicy并不reloadIgnoringLocalCacheData意味着不在缓存中存储任何数据,而是意味着忽略缓存中存储的任何内容并从源获取数据。

根据文档,使用 URLSession 的默认shared单例可以使用默认缓存

来自文档

共享会话使用共享的 URLCache、HTTPCookieStorage 和 URLCredentialStorage 对象,使用共享的自定义网络协议列表(使用 registerClass( :) 和 unregisterClass( :) 配置),并且基于默认配置。

尝试一下,我根据您上面提到的用例进行了尝试,它做了您想要的事情。