在项目中遇到这样的一个问题,图片返回的url因为是存在百度云上所以带authority认证的,即虽然是同一张图片,但是后缀不一致,这样就导致了sd_setImageUrl的方法中,每次默认都缓存新的一张图片,所以需要截取“?”前的内容,来作为指定的key进行缓存。
这里用到了SDWebImage的5.0版本后加入的context参数
具体代码如下所示:
+ (NSString *)getOtherCacheKey:(NSString *)urlStr {
NSString *keyString = [urlStr componentsSeparatedByString:@"?"].firstObject;
return keyString;
}
+ (void)cacheImgView:(UIImageView *)myImgView url:(NSString *)urlString placeholderImage:(NSString *)placeholderImage{
NSString *headUrlPre = [JCJDFunction getOtherCacheKey:urlString];
UIImage *cacheImage = [[SDImageCache sharedImageCache] imageFromCacheForKey:headUrlPre];
if (cacheImage != nil) {
myImgView.image = cacheImage;
} else {
NSURL *url = [NSURL URLWithString:urlString];
//通过context参数指定存储的key,指定的key为截取urlString中"?"前面的内容
SDWebImageCacheKeyFilter *cacheKeyFilter = [SDWebImageCacheKeyFilter cacheKeyFilterWithBlock:^NSString * _Nullable(NSURL * _Nonnull imageURL) {
if ([url isEqual:imageURL]) {
return headUrlPre;
} else {
return url.absoluteString;
}
}];
SDWebImageContext *context = [NSDictionary dictionaryWithObject:cacheKeyFilter forKey:SDWebImageContextCacheKeyFilter];
[myImgView sd_setImageWithURL:[NSURL URLWithString:cacheImage != nil ? headUrlPre : urlString] placeholderImage:[UIImage imageNamed:placeholderImage] options:0 context:context];
}
}
参考资料:
网友评论