2012-01-01 56 views
5

在我的申請,我現在用的是NSURLConnection方法加載JSON數據,看起來像這樣:NSURLConnection的將返回舊數據

NSURLRequest *request = [[NSURLRequest alloc] initWithURL: 
           [NSURL URLWithString:@"theurl"]]; 
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:request 
                   delegate:self]; 
[theConnection start]; 

我收到並保存在-didReceiveData:方法的數據,但如果更新我的我的服務器上的JSON文件,NSURLConnection仍然爲我提供舊的JSON,而文件正確上傳到服務器。只有當我從iPhone(或iPhone Simulator)中刪除整個應用程序並重建應用程序時,它纔會收到新的Json文件。

有沒有人知道這個問題的解決方案?

+0

聲音像結果被緩存,看到[這個答案](http://stackoverflow.com/questions/405151/is-it-possible-to-prevent-an-nsurlrequest-from-caching-data-or-remove-cached -dat) – Douglas 2012-01-01 19:37:51

+0

謝謝!你和傑西的答案對我有用! – Jelle 2012-01-01 19:59:13

回答

9

您需要告訴NSURLRequest重新評估(如果您的服務器發送適當的修改標頭)或不使用它的緩存。下面是從我JBAsyncImageView項目片段(提示:使用NSURLRequestReloadRevalidatingCacheDataNSURLRequestReloadIgnoringLocalCacheData):

// Create request 
self.imageRequest = [[NSURLRequest alloc] initWithURL:imageURL 
              cachePolicy:(self.cachesImage) ? NSURLRequestReturnCacheDataElseLoad : NSURLRequestReloadIgnoringLocalCacheData 
             timeoutInterval:self.downloadTimeoutInterval]; 

// Begin download 
self.imageData = nil; 
self.imageConnection = [[NSURLConnection alloc] initWithRequest:self.imageRequest 
                 delegate:self 
               startImmediately:YES]; 
+1

非常感謝你的回答!爲我工作! – Jelle 2012-01-01 19:51:09

+0

當iOS 7推出時,我遇到了這個問題。上述解決方案沒有解決我的問題。在嘗試了幾件不同的事情之後,我不得不使用下面的解決方案(添加時間戳來請求)。 – 2013-11-13 15:13:53

+0

該文檔說「NSURLRequestReloadIgnoringLocalCacheData」未實現? – 2015-03-10 13:10:49

5

防止請求緩存,最簡單的解決方案是在結束與當前時間添加時間戳參數:

http://example.com/api.json?my=args&timestamp=2344992923 
+1

實際上,告訴'NSURLRequest'重新評估或不緩存數據---而不是黑客HTTP請求可能更容易。對於AJAX請求,這將是最簡單的方法。然而,在iOS上,並非如此。 – 2012-01-01 20:01:50

+1

@JesseBunch時間戳方法在服務器端或代理緩存配置錯誤的情況下具有優勢。 – iHunter 2012-01-01 20:57:09

+0

確實如此,但是如果您告訴它不要使用緩存,則不必擔心。而對於它的價值,我並沒有讓你失望。 – 2012-01-01 20:58:50

相關問題