Cómo desactivar el almacenamiento en caché en Alamofire


Cuando envío una solicitud GET dos veces con Alamofire, obtengo la misma respuesta, pero espero una diferente. Me preguntaba si era por el caché, y si es así me gustaría saber cómo desactivarlo.

Author: Julian, 2015-08-25

8 answers

Swift 3, alamofire 4

Mi solución fue:

Creando extensión para Alamofire:

extension Alamofire.SessionManager{
    @discardableResult
    open func requestWithoutCache(
        _ url: URLConvertible,
        method: HTTPMethod = .get,
        parameters: Parameters? = nil,
        encoding: ParameterEncoding = URLEncoding.default,
        headers: HTTPHeaders? = nil)// also you can add URLRequest.CachePolicy here as parameter
        -> DataRequest
    {
        do {
            var urlRequest = try URLRequest(url: url, method: method, headers: headers)
            urlRequest.cachePolicy = .reloadIgnoringCacheData // <<== Cache disabled
            let encodedURLRequest = try encoding.encode(urlRequest, with: parameters)
            return request(encodedURLRequest)
        } catch {
            // TODO: find a better way to handle error
            print(error)
            return request(URLRequest(url: URL(string: "http://example.com/wrong_request")!))
        }
    }
}

Y usándolo:

Alamofire.SessionManager.default
            .requestWithoutCache("https://google.com/").response { response in
                print("Request: \(response.request)")
                print("Response: \(response.response)")
                print("Error: \(response.error)")
        }
 26
Author: Andrew,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-12-25 08:10:23

Tienes algunas opciones.

Deshabilitar el URLCache completamente

let manager: Manager = {
    let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
    configuration.URLCache = nil
    return Manager(configuration: configuration)
}()

Configuración de la Directiva Caché de solicitudes

let manager: Manager = {
    let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
    configuration.requestCachePolicy = .ReloadIgnoringLocalCacheData
    return Manager(configuration: configuration)
}()

Ambos enfoques deberían hacer el truco para usted. Para obtener más información, sugiero leer la documentación de NSURLSessionConfiguration y NSURLCache. Otra gran referencia es el artículo de NSHipster sobre NSURLCache.

 38
Author: cnoon,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-08-26 15:09:59

Esto es lo que funcionó para mí.

NSURLCache.sharedURLCache().removeAllCachedResponses()

Swift 3

URLCache.shared.removeAllCachedResponses()
 28
Author: Allanah Douglas,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-01-27 02:44:52

Otra opción si desea utilizar el administrador de Alamofire compartido sería hacer esto:

Alamofire.Manager.sharedInstance.session.configuration.requestCachePolicy = .ReloadIgnoringLocalCacheData

Después puede usar Alamofire.request(.GET, urlString).... con la nueva política de caché.

 6
Author: marosoaie,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-04-25 11:59:17

En Alamofire 4 y Swift 3:

// outside function, inside class
var sessionManager: SessionManager!

func someFunc() {
    let configuration = URLSessionConfiguration.default
    configuration.urlCache = nil
    let sessionManager = Alamofire.SessionManager(configuration: configuration)
    sessionManager.request("http://example.com/get").responseJSON { response in
        // ...
    }
}
 2
Author: Yifei He,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-12-15 10:21:41

[Este enfoque no deshabilita el almacenamiento en caché, simplemente se asegura de que los archivos almacenados en caché no se reutilizan]

Una forma más fácil de superar el problema de caché para una llamada en particular es simplemente agregar un número aleatorio en los parámetros de llamada.

Para Swift 3, puede usar, arc4random() para generar un número aleatorio.

 2
Author: Rao,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-11-15 11:25:57
func getImage(url: String, completion: @escaping (UIImage?) -> ()) {

    let urlRequest = URLRequest(url: URL(string: url)!)
    URLCache.shared.removeCachedResponse(for: urlRequest)
    //URLCache.shared.removeAllCachedResponses()

    Alamofire.request(url).responseData { (dataResponse) in
        guard let data = dataResponse.data else {
            return completion(nil)
        }
        completion(UIImage(data: data, scale:1))
    }
}
 2
Author: Warif Akhand Rishi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-12-18 13:04:15

Lo resolví haciendo

configuration.urlCache?.removeAllCachedResponses()
 0
Author: iAnurag,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-21 12:33:18