需求:tableView/collectionView加载若干图片,图片加载完成后,点击cell拿到图片在磁盘上的缓存地址。
看需求直接用SDWebImage,图片加载完成后
NSString *sdKey = [[SDWebImageManager sharedManager] cacheKeyForURL:url];
NSString *path = [[SDImageCache sharedImageCache] cachePathForKey:sdKey];
// 之后外界SDK
NSData *data = [NSData dataWithContentsOfFile:path];
问题出现了,data有时是空的,查看缓存地址,路径下确实有那张图片,但是图片名不对,发现是SDWebImageWaitStoreCache = 1 << 22标识符的问题,图片加载完成后,并没有立即写入磁盘
/**
* By default, when we load the image from network, the image will be written to the cache (memory and disk, controlled by your `storeCacheType` context option)
* This maybe an asynchronously operation and the final `SDInternalCompletionBlock` callback does not guarantee the disk cache written is finished and may cause logic error. (For example, you modify the disk data just in completion block, however, the disk cache is not ready)
* If you need to process with the disk cache in the completion block, you should use this option to ensure the disk cache already been written when callback.
* Note if you use this when using the custom cache serializer, or using the transformer, we will also wait until the output image data written is finished.
*/
SDWebImageWaitStoreCache = 1 << 22,
然后尝试[testImageView sd_setImageWithURL:placeholderImage:options]options里传入SDWebImageWaitStoreCache依然不行
最终解决方案,再加载一下,此时会把内存里的缓存写入磁盘再回调,不要问我为什么不直接给外界data,因为外界SDK就是要path啊。。。
+ (void)getSDWebImageCachePathWithURL:(NSURL *)url callBack:(void(^)(NSString *path))callBack {
SDWebImageOptions options = SDWebImageRetryFailed | SDWebImageLowPriority | SDWebImageWaitStoreCache;
[[SDWebImageManager sharedManager] loadImageWithURL:url options:options progress:nil completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, SDImageCacheType cacheType, BOOL finished, NSURL * _Nullable imageURL) {
dispatch_async(dispatch_get_main_queue(), ^{
NSString *sdKey = [[SDWebImageManager sharedManager] cacheKeyForURL:url];
NSString *path = [[SDImageCache sharedImageCache] cachePathForKey:sdKey];
!callBack ?: callBack(path);
});
}];
}