1. 程式人生 > >Swift之網路程式設計-請求快取

Swift之網路程式設計-請求快取

在網路程式設計的過程中,快取操作的應用十分廣泛

在使用快取技術過程中,需要的注意點:

1、經常更新的資料,不能使用快取技術

2、不經常更新的資料,果斷使用快取技術

3、如果存在大量請求,並且使用快取技術,則需要定期清除快取資料

如下附上快取操作程式碼

    override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
        let uri = "http://www.baidu.com";
        let url = NSURL(string: uri)!;
        let request = NSMutableURLRequest(URL: url);
        /**
        *  .設定快取策略
        *  .UseProtocolCachePolicy:依賴於請求頭的設定,預設狀態;
        *  .ReloadIgnoringLocalCacheData:忽略快取,重新請求伺服器
        *  .ReturnCacheDataElseLoad:有快取使用快取,無快取請求伺服器
        *  .ReturnCacheDataDontLoad:離線模式,有快取使用快取,無快取不請求伺服器
        */
        request.cachePolicy = NSURLRequestCachePolicy.ReturnCacheDataElseLoad;
        // 獲得全域性快取物件
        let cache = NSURLCache.sharedURLCache();
        //
        let response = cache.cachedResponseForRequest(request);
        if response == nil {
            // 本地無快取
            println("no cache");
        } else {
            // 本地有快取
            println("exist cache");
            // 將當前請求的快取資料刪除,獲取最新資料
            cache.removeCachedResponseForRequest(request);
            // 清除所有快取
            // cache.removeAllCachedResponses();
        }

        NSURLConnection(request: request, delegate: self);
    }