swift -> h缓存机制 加载 网络图片

let urlStr = NSURL(string: "https://s.yimg.com/dh/ap/default/130909/y_200_a.png")
        let request = NSMutableURLRequest(url: urlStr as! URL);
        /**
         *  .设置缓存策略
         *  .UseProtocolCachePolicy:依赖于请求头的设置,默认状态;
         *  .ReloadIgnoringLocalCacheData:忽略缓存,重新请求服务器
         *  .ReturnCacheDataElseLoad:有缓存使用缓存,无缓存请求服务器
         *  .ReturnCacheDataDontLoad:离线模式,有缓存使用缓存,无缓存不请求服务器
         */
        request.cachePolicy = .returnCacheDataElseLoad//策略
        let cache = URLCache.shared;//这个可以设置为全局
        let response = cache.cachedResponse(for: request as URLRequest);
        if(response == nil){//如果没有缓存
            let data = NSData(contentsOf: urlStr! as URL)
            let image = UIImage(data: data! as Data)
            let imageView = UIImageView(image: image)
            self.view.addSubview(imageView)
            print("no cache");
        }else{//如果有缓存
            let image = UIImage(data: (response?.data)!)
            let imageView = UIImageView(image: image)
            self.view.addSubview(imageView)
            
            print("yes cache");
            
        }

相关推荐