Use the @synchronized to access NSURLCache to fix the potential thread-safe problem, also fix that we always use shared cache but not follow session's configuration

This commit is contained in:
DreamPiggy 2018-01-14 17:55:54 +08:00
parent 09e90b5215
commit 86d056f3c9
1 changed files with 16 additions and 8 deletions

View File

@ -135,14 +135,6 @@ typedef NSMutableDictionary<NSString *, id> SDCallbacksDictionary;
}];
}
#endif
if (self.options & SDWebImageDownloaderIgnoreCachedResponse) {
// Grab the cached data for later check
NSCachedURLResponse *cachedResponse = [[NSURLCache sharedURLCache] cachedResponseForRequest:self.request];
if (cachedResponse) {
self.cachedData = cachedResponse.data;
}
}
NSURLSession *session = self.unownedSession;
if (!self.unownedSession) {
NSURLSessionConfiguration *sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration];
@ -159,6 +151,22 @@ typedef NSMutableDictionary<NSString *, id> SDCallbacksDictionary;
session = self.ownedSession;
}
if (self.options & SDWebImageDownloaderIgnoreCachedResponse) {
// Grab the cached data for later check
NSURLCache *URLCache = session.configuration.URLCache;
if (!URLCache) {
URLCache = [NSURLCache sharedURLCache];
}
NSCachedURLResponse *cachedResponse;
// NSURLCache's `cachedResponseForRequest:` is not thread-safe, see https://developer.apple.com/documentation/foundation/nsurlcache#2317483
@synchronized (URLCache) {
cachedResponse = [URLCache cachedResponseForRequest:self.request];
}
if (cachedResponse) {
self.cachedData = cachedResponse.data;
}
}
self.dataTask = [session dataTaskWithRequest:self.request];
self.executing = YES;
}