swift -> h cache mechanism to load network images

 

        
        let urlStr = NSURL(string: "https://s.yimg.com/dh/ap/default/130909/y_200_a.png")
        let request = NSMutableURLRequest(url: urlStr as! URL);
        /**
         * .Set cache policy
         * .UseProtocolCachePolicy: depends on the setting of the request header, the default state;
         *.ReloadIgnoringLocalCacheData: Ignore the cache and re-request the server
         *.ReturnCacheDataElseLoad: There is a cache to use the cache, no cache to request the server
         * .ReturnCacheDataDontLoad: Offline mode, there is cache to use cache, no cache does not request the server
         */
        request.cachePolicy = .returnCacheDataElseLoad//策略
        let cache = URLCache.shared;//This can be set globally
        let response = cache.cachedResponse(for: request as URLRequest);
        if(response == nil){//If there is no cache
            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{//If there is a cache
            let image = UIImage(data: (response?.data)!)
            let imageView = UIImageView(image: image)
            self.view.addSubview(imageView)
            
            print("yes cache");
            
        }

 

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326177749&siteId=291194637