iOS Download Image In The Same URL

简述

基于项目需求,上传头像成功后,iOS、Android、web端三端需要实时更新到最新的头像。

考虑到以上需求,由以下三种解决方式:

  • 通过长连接,服务器通知用户更新。

  • 上传头像带有时间参数。前端通过更新数据来比对URL是否发生变化,决定是否更新头像。

  • 通过ETag或者Last-Modified来判断当前请求资源是否改变。

目前所有项目中,头像URL都是唯一不变的,并且没有通过长连接的方式通知用户更新,所以都是通过ETag或者Last-Modified来判断当前请求资源是否改变。

之前的项目通过Last-Modified的方式,这次则通过ETag的方式。

注意:

ETag对比Last-Modified的优势

1、一些文件也许会周期性的更改,但是他的内容并不改变(仅仅改变的修改时间),这个时候我们并不希望客户端认为这个文件被修改了,而重新GET;

2、某些文件修改非常频繁,比如在秒以下的时间内进行修改,(比方说1s内修改了N次),If-Modified-Since能检查到的粒度是s级的,这种修改无法判断(或者说UNIX记录MTIME只能精确到秒);

3、某些服务器不能精确的得到文件的最后修改时间。

Objective-C & SDWebImage

在SDImage中,我们可以通过SDWebImageDownloader的imgDownloader.headersFilter配置读取本地图片的修改时间给“If-Modified-Since”,如果服务器返回状态304,说明资源无需更新,否则返回状态200和请求的资源内容。

代码配置如下:

- (void)sdWebDownloaderRegister {
    SDWebImageDownloader *imgDownloader = SDWebImageManager.sharedManager.imageDownloader;
    imgDownloader.headersFilter = ^NSDictionary *(NSURL *url, NSDictionary *headers) {
        NSFileManager *fm = [[NSFileManager alloc] init];
        NSString *imgKey = [SDWebImageManager.sharedManager cacheKeyForURL:url];
        NSString *imgPath = [SDWebImageManager.sharedManager.imageCache defaultCachePathForKey:imgKey];
        NSDictionary *fileAttr = [fm attributesOfItemAtPath:imgPath error:nil];
        
        NSMutableDictionary *mutableHeaders = [headers mutableCopy];
        
        NSDate *lastModifiedDate = nil;
        if (fileAttr.count > 0) {
            lastModifiedDate = (NSDate *)fileAttr[NSFileModificationDate];
        }
        
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        formatter.timeZone = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];
        formatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
        formatter.dateFormat = @"EEE, dd MMM yyyy HH:mm:ss z";
        
        NSString *lastModifiedStr = [formatter stringFromDate:lastModifiedDate];
        lastModifiedStr = lastModifiedStr.length > 0 ? lastModifiedStr : @"";
        [mutableHeaders setValue:lastModifiedStr forKey:@"If-Modified-Since"];
        
        return mutableHeaders;
    };
}

另外需要注意的是option设置为SDWebImageRefreshCached

通过查阅HTTP协议相关的资料得知,与服务器返回的Last-Modified相对应的request header里可以加一个名为If-Modified-Since的key,value即是服务器回传的服务端图片最后被修改的时间,第一次图片请求时If-Modified-Since的值为空,第二次及以后的客户端请求会把服务器回传的Last-Modified值作为If-Modified-Since的值传给服务器,这样服务器每次接收到图片请求时就将If-Modified-Since与Last-Modified进行比较,如果客户端图片已陈旧那么返回状态码200、Last-Modified、图片内容,客户端存储Last-Modified和图片;如果客户端图片是最新的那么返回304 Not Modified、不会返回Last-Modified、图片内容。

Swift & Kingfisher

从响应中获取ETag

首先,我们必须知道图像的ETag。通过符合ImageDownloaderDelegate我们可以ETag从响应头中提取条目并存储它。

extension AppDelegate: ImageDownloaderDelegate {
    func imageDownloader(_ downloader: ImageDownloader, didDownload image: Image, for url: URL, with response: URLResponse?) {
        if let httpResponse = response as? HTTPURLResponse,
            let etag = httpResponse.allHeaderFields["Etag"] as? String {
            let dictionaryKey = "image-etags"

            var dictionary = UserDefaults.standard.dictionary(forKey: dictionaryKey) as? [String: String]
            if dictionary == nil {
                dictionary = [String: String]()
            }

            let hash = KingfisherManager.shared.cache.hash(forKey: url.absoluteString)
            dictionary![hash] = etag
            UserDefaults.standard.set(dictionary, forKey: dictionaryKey)
            UserDefaults.standard.synchronize()
        }
    }
}

我们在这里存储ETag的URL作为密钥。这是因为Kingfisher使用哈希作为匿名的磁盘文件名称。存储的ETag将在稍后请求相同的URL时发送到服务器。

为缓存的图像维护Etags

在将Etag发送到服务器时,我们需要确保映像位于磁盘缓存中。由于磁盘高速缓存具有过期持续时间和大小限制,因此可能会从磁盘高速缓存中清除某些文件。您需要知道从磁盘中删除哪些文件,并删除相应的Etags。KingfisherDidCleanDiskCacheNotification有助于。

在整个应用程序生命周期中的活跃地方观察此通知(AppDelegate是一个很好的示例),并使用散列删除Etags。

    private func kingfisherConfiguration() {
        KingfisherManager.shared.downloader.delegate = self
        NotificationCenter.default.addObserver(self,
                                               selector: #selector(diskImageCacheCleaned(notification:)),
                                               name: NSNotification.Name(rawValue: KingfisherDiskCacheCleanedHashKey), object: KingfisherManager.shared.cache)
    }
    
    @objc func diskImageCacheCleaned(notification: Notification) {
        let dictionaryKey = "image-etags"

        let userDefaults = UserDefaults.standard
        if let dictionary = userDefaults.dictionary(forKey: dictionaryKey) as? [String: String], let hashes = notification.userInfo?[KingfisherDiskCacheCleanedHashKey] as? [String] {
            var result = dictionary
            for hash in hashes {
                result.removeValue(forKey: hash)
            }
            userDefaults.set(result, forKey: dictionaryKey)
            userDefaults.synchronize()
        }
    }

请注意,KingfisherDidCleanDiskCacheNotification只有在缓存文件过期或总大小超过最大允许大小时才会发送。如果您手动清除磁盘缓存,则应该自己删除所有存储的Etags。

修改请求头信息

最后,我们将在标题中的“If-None-Match”字段中发送Etag以及请求。用于requestModifier在发送请求之前修改请求。我们还必须KingfisherOptions.ForceRefresh首先发送请求,而不是在缓存中搜索:

        let modifiter = AnyModifier.init { (request) -> URLRequest? in
            var modifyRequest = request
            let hash = KingfisherManager.shared.cache.hash(forKey: (request.url?.absoluteString)!)
            if let dictionary = UserDefaults.standard.dictionary(forKey: "image-etags"), let etag = dictionary[hash] as? String {
                modifyRequest.setValue(etag, forHTTPHeaderField: "If-None-Match")

            }
            return modifyRequest
        }

        imageView.kf.setImage(with: ImageResource.init(downloadURL: URL.init(string: currentUrl)), placeholder: nil, options: [.forceRefresh], progressBlock: nil, completionHandler: nil)

如果服务器返回304 Not Modified,Kingfisher将使用缓存的图像。否则,下载新版本。

requestModifier如果你不再使用它,请记住清理它,特别是如果你指的self是它。这是一个strong财产!

iOS Download Image In The Same URL_第1张图片
304示例1
iOS Download Image In The Same URL_第2张图片
304示例1

命令行查看头部信息

命令:curl -I URL

iOS Download Image In The Same URL_第3张图片
header

参考文献:

  1. 百度百科
  2. Kingfisher

你可能感兴趣的:(iOS Download Image In The Same URL)