2015-06-09 3 views
10

Ho impostato la politica della cache per richiedere in Alamofire di ignorare la cache locale.Alamofire caricamento dalla cache anche quando la politica della cache è impostata su ReloadIgnoringLocalAndRemoteCacheData

Quindi carico un viewcontroller con una connessione di rete, quindi disconnetto la connessione di rete, uccido l'app ed eseguo di nuovo.

Ora nessun errore a disposizione della rete non viene visualizzato (cioè alamofire doesnt creare l'oggetto NSError) creato, invece app funziona come se la richiesta è riuscita recupero dei dati dalla cache obviously.And la cosa strana è il quando ho cercato di esaminare i dati memorizzati nella cache utilizzando

NSURLCache.sharedURLCache().cachedResponseForRequest(request) 

nullo viene restituito benche 'i dati sono stati dalla cache ..

l'unico modo che potrebbe impedire cache risposte è eseguire NSURLCache.sharedURLCache().removeAllCachedResponses()

let request = NSURLRequest(URL: NSURL(string: url)!, cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringLocalAndRemoteCacheData, timeoutInterval: 100) 

    Alamofire.manager.request(method, request, parameters:params) 
    .responseJSON { (request, response, data, error) in 
     if let anError = error { 
      if anError.code == NSURLErrorNotConnectedToInternet { 
       UIAlertView(title: "Alert", message: "No Network Connection Available", delegate: nil, cancelButtonTitle: "ok").show() 
      }  

     } else if let data: AnyObject = data { 
      println(NSURLCache.sharedURLCache().cachedResponseForRequest(request)) 
//prints nil 

    } 

} 
} 

Quello che voglio fare è caricare i dati dalla cache solo se la connessione di rete non è disponibile, qualcosa come la modalità offline limitata. Come fare?

risposta

10

sto usando in questo modo in un progetto e che sta funzionando:

let mutableURLRequest = NSMutableURLRequest(URL: SERVICEURL) 
mutableURLRequest.HTTPMethod = "POST" 

mutableURLRequest.HTTPBody = self.createJson() 
mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") 
mutableURLRequest.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringCacheData 

request(mutableURLRequest).validate().responseJSON{ response in... 

Speranza che aiuta.

+0

Grazie. Questo ha funzionato perfettamente. – iksnae

+0

qual è la richiesta? –

+0

@HongZhou È un metodo di convenienza di Alamofire. Puoi usarlo come "Alamofire.request (mutableURLRequest) .validate(). ResponseJSON {response in ..." –

1

Grazie a @ FábioSalata ho risolto il mio problema come questo.

var req = URLRequest(url: URL(string: "<URL>")!) 
req.httpMethod = "GET" 
req.setValue("application/json", forHTTPHeaderField: "Content-Type") 
req.setValue("<Auth KEY>", forHTTPHeaderField:"Authorization") 
req.cachePolicy = NSURLRequest.CachePolicy.reloadIgnoringCacheData 

Alamofire.request(req).validate().responseJSON { response in ...