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);
    }


你可能感兴趣的:(swift)