针对我们下载图片地址的动态性. 例如: 服务器给到我们图片的地址, 只是一段字符: NSString * urlStr = @"les://BEC0200F32374CD1B2255F4449B61CF8"
然后利用urlStr去发送post请求, 获取到对应的url 和 header参数.
例如: downURL: https://sample.com
header参数: X-Les-Date --> date
X-Les-Length --> length
Authorization --> auth
这时, 需要自行构造https请求头, 请求头header的参数是动态.
那么这时如何利用SDWebImage框架来做呢:
代码如下:
先创建类属性, headersDict ,
key: 图片地址downURL value: 一个字典保存有header的各种参数
NSMutableDictionary * header = [NSMutableDictionary dictionary];
[header setValue:date forKey:@"X-Les-Date"];
[header setValue:length forKey:@" X-Les-Length"];
[header setValue:auth forKey:@"Authorization"];
[self.headersDict setValue:header forKey:downURL];
//这里来设置header, 利用headersFilter, 将对应的downURL的header取出来设置好.
[SDWebImageManager sharedManager].imageDownloader.headersFilter = ^(NSURL *url, NSDictionary * headers){
//这里的url, 就是来下载的downURL
NSMutableDictionary * headerDic = [NSMutableDictionary dictionary];
[headerDic setDictionary:headers];
[headerDic setDictionary:[self.headersDict valueForKey:url.absoluteString]];
return headerDic;
};
// options: SDWebImageAllowInvalidSSLCertificates针对https地址没有域名或者证书过期等问题, 跳过检测, 后续会有另外方法在解决
[[SDWebImageManager sharedManager] downloadImageWithURL:[NSURL URLWithString:downURL] options:SDWebImageAllowInvalidSSLCertificates progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
//如果要传出去缓存的地址
NSString *cacheImageKey = [[SDWebImageManager sharedManager] cacheKeyForURL:[NSURL URLWithString:downURL]];
NSString *cacheImagePath = [[SDImageCache sharedImageCache] defaultCachePathForKey:cacheImageKey];
NSLog(@"哈哈😝%@", cacheImagePath);
if (!image) {
// 外层自己封装的回调block, 需要传出去什么值,自己定
completion(NO, @"下载图片失败", nil, nil);
}else{
completion(YES, nil, image, cacheImagePath);
}
}];
如有问题, 请进 iOS 交流群, 475273865