2015-01-07 77 views
1

我在iOS 8.0 Swift應用中遇到緩存問題。這是我做了什麼:NSURLCache不能與NSURLSession配合使用

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { 
    let URLCache = NSURLCache(memoryCapacity: 500 * 1024 * 1024, diskCapacity: 500 * 1024 * 1024, diskPath: nil) 
    NSURLCache.setSharedURLCache(URLCache) 
    return true 
} 

我有一個運行在初始化這個代碼的自定義視圖:

let config = NSURLSessionConfiguration.defaultSessionConfiguration() 
config.URLCache = NSURLCache.sharedURLCache() 
config.requestCachePolicy = NSURLRequestCachePolicy.UseProtocolCachePolicy 
session = NSURLSession(configuration: config) 

然後我運行這段代碼時,我打一個按鈕:

let request = NSMutableURLRequest(URL: NSURL(string: "http://localhost:8080/test")!, cachePolicy: NSURLRequestCachePolicy.UseProtocolCachePolicy, timeoutInterval: 100) 
session!.dataTaskWithRequest(request, completionHandler: { (data, res, error) -> Void in 
    let test = JSON(data: data, options: NSJSONReadingOptions.AllowFragments, error: nil) 
    println(test) 
}).resume() 

我的本地主機/測試url是一個簡單的端點,我已經設置爲返回隨機JSON,幷包含一個像這樣的Cache-Control標頭:

Cache-Control:max-age=600 

我的問題是請求永遠不會寫入緩存。我也嘗試將「UseProtocolCachePolicy」更改爲「ReturnCacheDataElseLoad」,但仍不會寫入緩存。

這裏是踢球者:如果我使用NSURLConnection(而不是NSURLSession)進行一次調用,它將被寫入緩存。然後所有的調用都從緩存中加載得很好。我該如何解決?

+0

我有相同的代碼,並且緩存也不適用於我。 – andyPaul

回答

0

NSURLCache和NSURLSession目前似乎是最好的buggy,可能會損壞。我不需要後臺下載或類似的東西,所以我選擇使用現金:https://github.com/nnoble/Cash。它適合我的需求。

相關問題