Browse files

Merge pull request #607 from akhenakh/reformat_code

Code standardization
  • Loading branch information...
2 parents c00c2e0 + 03eeb58 commit 42f97369726f1ee282b40b63616e339adfcb2c8a @rs committed Jan 6, 2014
View
2 README.md
@@ -139,7 +139,7 @@ key is an application unique identifier for the image to cache. It is generally
the image.
```objective-c
-SDImageCache *imageCache = [SDImageCache.alloc initWithNamespace:@"myNamespace"];
+SDImageCache *imageCache = [[SDImageCache alloc] initWithNamespace:@"myNamespace"];
[imageCache queryDiskCacheForKey:myCacheKey done:^(UIImage *image)
{
// image is not nil if image was found
View
43 SDWebImage/MKAnnotationView+WebCache.m
@@ -13,53 +13,42 @@
@implementation MKAnnotationView (WebCache)
-- (void)setImageWithURL:(NSURL *)url
-{
+- (void)setImageWithURL:(NSURL *)url {
[self setImageWithURL:url placeholderImage:nil options:0 completed:nil];
}
-- (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder
-{
+- (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder {
[self setImageWithURL:url placeholderImage:placeholder options:0 completed:nil];
}
-- (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options
-{
+- (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options {
[self setImageWithURL:url placeholderImage:placeholder options:options completed:nil];
}
-- (void)setImageWithURL:(NSURL *)url completed:(SDWebImageCompletedBlock)completedBlock
-{
+- (void)setImageWithURL:(NSURL *)url completed:(SDWebImageCompletedBlock)completedBlock {
[self setImageWithURL:url placeholderImage:nil options:0 completed:completedBlock];
}
-- (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletedBlock)completedBlock
-{
+- (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletedBlock)completedBlock {
[self setImageWithURL:url placeholderImage:placeholder options:0 completed:completedBlock];
}
-- (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletedBlock)completedBlock
-{
+- (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletedBlock)completedBlock {
[self cancelCurrentImageLoad];
self.image = placeholder;
-
- if (url)
- {
+
+ if (url) {
__weak MKAnnotationView *wself = self;
- id<SDWebImageOperation> operation = [SDWebImageManager.sharedManager downloadWithURL:url options:options progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished)
- {
+ id <SDWebImageOperation> operation = [SDWebImageManager.sharedManager downloadWithURL:url options:options progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished) {
if (!wself) return;
- dispatch_main_sync_safe(^
- {
+ dispatch_main_sync_safe(^{
__strong MKAnnotationView *sself = wself;
if (!sself) return;
- if (image)
- {
+ if (image) {
sself.image = image;
}
- if (completedBlock && finished)
- {
+ if (completedBlock && finished) {
completedBlock(image, error, cacheType);
}
});
@@ -68,12 +57,10 @@ - (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder opt
}
}
-- (void)cancelCurrentImageLoad
-{
+- (void)cancelCurrentImageLoad {
// Cancel in progress downloader from queue
- id<SDWebImageOperation> operation = objc_getAssociatedObject(self, &operationKey);
- if (operation)
- {
+ id <SDWebImageOperation> operation = objc_getAssociatedObject(self, &operationKey);
+ if (operation) {
[operation cancel];
objc_setAssociatedObject(self, &operationKey, nil, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
View
10 SDWebImage/SDImageCache.h
@@ -9,22 +9,20 @@
#import <Foundation/Foundation.h>
#import "SDWebImageCompat.h"
-enum SDImageCacheType
-{
+typedef NS_ENUM(NSInteger, SDImageCacheType) {
/**
* The image wasn't available the SDWebImage caches, but was downloaded from the web.
*/
- SDImageCacheTypeNone = 0,
+ SDImageCacheTypeNone,
/**
* The image was obtained from the disk cache.
*/
- SDImageCacheTypeDisk,
+ SDImageCacheTypeDisk,
/**
* The image was obtained from the memory cache.
*/
- SDImageCacheTypeMemory
+ SDImageCacheTypeMemory
};
-typedef enum SDImageCacheType SDImageCacheType;
/**
* SDImageCache maintains a memory cache and an optional disk cache. Disk cache write operations are performed
View
272 SDWebImage/SDImageCache.m
@@ -10,22 +10,18 @@
#import "SDWebImageDecoder.h"
#import "UIImage+MultiFormat.h"
#import <CommonCrypto/CommonDigest.h>
-#import <mach/mach.h>
-#import <mach/mach_host.h>
static const NSInteger kDefaultCacheMaxCacheAge = 60 * 60 * 24 * 7; // 1 week
// PNG signature bytes and data (below)
static unsigned char kPNGSignatureBytes[8] = {0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A};
static NSData *kPNGSignatureData = nil;
BOOL ImageDataHasPNGPreffix(NSData *data);
-BOOL ImageDataHasPNGPreffix(NSData *data)
-{
+
+BOOL ImageDataHasPNGPreffix(NSData *data) {
NSUInteger pngSignatureLength = [kPNGSignatureData length];
- if ([data length] >= pngSignatureLength)
- {
- if ([[data subdataWithRange:NSMakeRange(0, pngSignatureLength)] isEqualToData:kPNGSignatureData])
- {
+ if ([data length] >= pngSignatureLength) {
+ if ([[data subdataWithRange:NSMakeRange(0, pngSignatureLength)] isEqualToData:kPNGSignatureData]) {
return YES;
}
}
@@ -43,32 +39,26 @@ @interface SDImageCache ()
@end
-@implementation SDImageCache
-{
+@implementation SDImageCache {
NSFileManager *_fileManager;
}
-+ (SDImageCache *)sharedImageCache
-{
++ (SDImageCache *)sharedImageCache {
static dispatch_once_t once;
static id instance;
- dispatch_once(&once, ^
- {
- instance = self.new;
+ dispatch_once(&once, ^{
+ instance = [self new];
kPNGSignatureData = [NSData dataWithBytes:kPNGSignatureBytes length:8];
});
return instance;
}
-- (id)init
-{
+- (id)init {
return [self initWithNamespace:@"default"];
}
-- (id)initWithNamespace:(NSString *)ns
-{
- if ((self = [super init]))
- {
+- (id)initWithNamespace:(NSString *)ns {
+ if ((self = [super init])) {
NSString *fullNamespace = [@"com.hackemist.SDWebImageCache." stringByAppendingString:ns];
// Create IO serial queue
@@ -85,9 +75,8 @@ - (id)initWithNamespace:(NSString *)ns
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
_diskCachePath = [paths[0] stringByAppendingPathComponent:fullNamespace];
- dispatch_sync(_ioQueue, ^
- {
- _fileManager = NSFileManager.new;
+ dispatch_sync(_ioQueue, ^{
+ _fileManager = [NSFileManager new];
});
#if TARGET_OS_IPHONE
@@ -112,72 +101,59 @@ - (id)initWithNamespace:(NSString *)ns
return self;
}
-- (void)dealloc
-{
+- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self];
SDDispatchQueueRelease(_ioQueue);
}
-- (void)addReadOnlyCachePath:(NSString *)path
-{
- if (!self.customPaths)
- {
- self.customPaths = NSMutableArray.new;
+- (void)addReadOnlyCachePath:(NSString *)path {
+ if (!self.customPaths) {
+ self.customPaths = [NSMutableArray new];
}
- if (![self.customPaths containsObject:path])
- {
+ if (![self.customPaths containsObject:path]) {
[self.customPaths addObject:path];
}
}
#pragma mark SDImageCache (private)
-- (NSString *)cachePathForKey:(NSString *)key inPath:(NSString *)path
-{
+- (NSString *)cachePathForKey:(NSString *)key inPath:(NSString *)path {
NSString *filename = [self cachedFileNameForKey:key];
return [path stringByAppendingPathComponent:filename];
}
-- (NSString *)defaultCachePathForKey:(NSString *)key
-{
+- (NSString *)defaultCachePathForKey:(NSString *)key {
return [self cachePathForKey:key inPath:self.diskCachePath];
}
-- (NSString *)cachedFileNameForKey:(NSString *)key
-{
+- (NSString *)cachedFileNameForKey:(NSString *)key {
const char *str = [key UTF8String];
- if (str == NULL)
- {
+ if (str == NULL) {
str = "";
}
unsigned char r[CC_MD5_DIGEST_LENGTH];
CC_MD5(str, (CC_LONG)strlen(str), r);
NSString *filename = [NSString stringWithFormat:@"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
- r[0], r[1], r[2], r[3], r[4], r[5], r[6], r[7], r[8], r[9], r[10], r[11], r[12], r[13], r[14], r[15]];
+ r[0], r[1], r[2], r[3], r[4], r[5], r[6], r[7], r[8], r[9], r[10], r[11], r[12], r[13], r[14], r[15]];
return filename;
}
#pragma mark ImageCache
-- (void)storeImage:(UIImage *)image recalculateFromImage:(BOOL)recalculate imageData:(NSData *)imageData forKey:(NSString *)key toDisk:(BOOL)toDisk
-{
- if (!image || !key)
- {
+- (void)storeImage:(UIImage *)image recalculateFromImage:(BOOL)recalculate imageData:(NSData *)imageData forKey:(NSString *)key toDisk:(BOOL)toDisk {
+ if (!image || !key) {
return;
}
[self.memCache setObject:image forKey:key cost:image.size.height * image.size.width * image.scale];
- if (toDisk)
- {
- dispatch_async(self.ioQueue, ^
- {
+ if (toDisk) {
+ dispatch_async(self.ioQueue, ^{
NSData *data = imageData;
- if (image && (recalculate || !data))
- {
+ if (image && (recalculate || !data)) {
#if TARGET_OS_IPHONE
// We need to determine if the image is a PNG or a JPEG
// PNGs are easier to detect because they have a unique signature (http://www.w3.org/TR/PNG-Structure.html)
@@ -189,31 +165,26 @@ - (void)storeImage:(UIImage *)image recalculateFromImage:(BOOL)recalculate image
BOOL imageIsPng = YES;
// But if we have an image data, we will look at the preffix
- if ([imageData length] >= [kPNGSignatureData length])
- {
+ if ([imageData length] >= [kPNGSignatureData length]) {
imageIsPng = ImageDataHasPNGPreffix(imageData);
}
- if (imageIsPng)
- {
+ if (imageIsPng) {
data = UIImagePNGRepresentation(image);
}
- else
- {
+ else {
data = UIImageJPEGRepresentation(image, (CGFloat)1.0);
}
#else
data = [NSBitmapImageRep representationOfImageRepsInArray:image.representations usingType: NSJPEGFileType properties:nil];
#endif
}
- if (data)
- {
+ if (data) {
// Can't use defaultManager another thread
- NSFileManager *fileManager = NSFileManager.new;
+ NSFileManager *fileManager = [NSFileManager new];
- if (![fileManager fileExistsAtPath:_diskCachePath])
- {
+ if (![fileManager fileExistsAtPath:_diskCachePath]) {
[fileManager createDirectoryAtPath:_diskCachePath withIntermediateDirectories:YES attributes:nil error:NULL];
}
@@ -223,63 +194,52 @@ - (void)storeImage:(UIImage *)image recalculateFromImage:(BOOL)recalculate image
}
}
-- (void)storeImage:(UIImage *)image forKey:(NSString *)key
-{
+- (void)storeImage:(UIImage *)image forKey:(NSString *)key {
[self storeImage:image recalculateFromImage:YES imageData:nil forKey:key toDisk:YES];
}
-- (void)storeImage:(UIImage *)image forKey:(NSString *)key toDisk:(BOOL)toDisk
-{
+- (void)storeImage:(UIImage *)image forKey:(NSString *)key toDisk:(BOOL)toDisk {
[self storeImage:image recalculateFromImage:YES imageData:nil forKey:key toDisk:toDisk];
}
-- (BOOL)diskImageExistsWithKey:(NSString *)key
-{
+- (BOOL)diskImageExistsWithKey:(NSString *)key {
__block BOOL exists = NO;
- dispatch_sync(_ioQueue, ^
- {
+ dispatch_sync(_ioQueue, ^{
exists = [_fileManager fileExistsAtPath:[self defaultCachePathForKey:key]];
});
return exists;
}
-- (UIImage *)imageFromMemoryCacheForKey:(NSString *)key
-{
+- (UIImage *)imageFromMemoryCacheForKey:(NSString *)key {
return [self.memCache objectForKey:key];
}
-- (UIImage *)imageFromDiskCacheForKey:(NSString *)key
-{
+- (UIImage *)imageFromDiskCacheForKey:(NSString *)key {
// First check the in-memory cache...
UIImage *image = [self imageFromMemoryCacheForKey:key];
- if (image)
- {
+ if (image) {
return image;
}
// Second check the disk cache...
UIImage *diskImage = [self diskImageForKey:key];
- if (diskImage)
- {
+ if (diskImage) {
CGFloat cost = diskImage.size.height * diskImage.size.width * diskImage.scale;
[self.memCache setObject:diskImage forKey:key cost:cost];
}
return diskImage;
}
-- (NSData *)diskImageDataBySearchingAllPathsForKey:(NSString *)key
-{
+- (NSData *)diskImageDataBySearchingAllPathsForKey:(NSString *)key {
NSString *defaultPath = [self defaultCachePathForKey:key];
NSData *data = [NSData dataWithContentsOfFile:defaultPath];
- if (data)
- {
+ if (data) {
return data;
}
- for (NSString *path in self.customPaths)
- {
+ for (NSString *path in self.customPaths) {
NSString *filePath = [self cachePathForKey:key inPath:path];
NSData *imageData = [NSData dataWithContentsOfFile:filePath];
if (imageData) {
@@ -290,65 +250,53 @@ - (NSData *)diskImageDataBySearchingAllPathsForKey:(NSString *)key
return nil;
}
-- (UIImage *)diskImageForKey:(NSString *)key
-{
+- (UIImage *)diskImageForKey:(NSString *)key {
NSData *data = [self diskImageDataBySearchingAllPathsForKey:key];
- if (data)
- {
+ if (data) {
UIImage *image = [UIImage sd_imageWithData:data];
image = [self scaledImageForKey:key image:image];
image = [UIImage decodedImageWithImage:image];
return image;
}
- else
- {
+ else {
return nil;
}
}
-- (UIImage *)scaledImageForKey:(NSString *)key image:(UIImage *)image
-{
+- (UIImage *)scaledImageForKey:(NSString *)key image:(UIImage *)image {
return SDScaledImageForKey(key, image);
}
-- (NSOperation *)queryDiskCacheForKey:(NSString *)key done:(void (^)(UIImage *image, SDImageCacheType cacheType))doneBlock
-{
- NSOperation *operation = NSOperation.new;
+- (NSOperation *)queryDiskCacheForKey:(NSString *)key done:(void (^)(UIImage *image, SDImageCacheType cacheType))doneBlock {
+ NSOperation *operation = [NSOperation new];
if (!doneBlock) return nil;
- if (!key)
- {
+ if (!key) {
doneBlock(nil, SDImageCacheTypeNone);
return nil;
}
// First check the in-memory cache...
UIImage *image = [self imageFromMemoryCacheForKey:key];
- if (image)
- {
+ if (image) {
doneBlock(image, SDImageCacheTypeMemory);
return nil;
}
- dispatch_async(self.ioQueue, ^
- {
- if (operation.isCancelled)
- {
+ dispatch_async(self.ioQueue, ^{
+ if (operation.isCancelled) {
return;
}
- @autoreleasepool
- {
+ @autoreleasepool {
UIImage *diskImage = [self diskImageForKey:key];
- if (diskImage)
- {
+ if (diskImage) {
CGFloat cost = diskImage.size.height * diskImage.size.width * diskImage.scale;
[self.memCache setObject:diskImage forKey:key cost:cost];
}
- dispatch_main_sync_safe(^
- {
+ dispatch_main_sync_safe(^{
doneBlock(diskImage, SDImageCacheTypeDisk);
});
}
@@ -357,48 +305,38 @@ - (NSOperation *)queryDiskCacheForKey:(NSString *)key done:(void (^)(UIImage *im
return operation;
}
-- (void)removeImageForKey:(NSString *)key
-{
+- (void)removeImageForKey:(NSString *)key {
[self removeImageForKey:key fromDisk:YES];
}
-- (void)removeImageForKey:(NSString *)key fromDisk:(BOOL)fromDisk
-{
- if (key == nil)
- {
+- (void)removeImageForKey:(NSString *)key fromDisk:(BOOL)fromDisk {
+ if (key == nil) {
return;
}
[self.memCache removeObjectForKey:key];
- if (fromDisk)
- {
- dispatch_async(self.ioQueue, ^
- {
+ if (fromDisk) {
+ dispatch_async(self.ioQueue, ^{
[[NSFileManager defaultManager] removeItemAtPath:[self defaultCachePathForKey:key] error:nil];
});
}
}
-- (void)setMaxMemoryCost:(NSUInteger)maxMemoryCost
-{
+- (void)setMaxMemoryCost:(NSUInteger)maxMemoryCost {
self.memCache.totalCostLimit = maxMemoryCost;
}
-- (NSUInteger)maxMemoryCost
-{
+- (NSUInteger)maxMemoryCost {
return self.memCache.totalCostLimit;
}
-- (void)clearMemory
-{
+- (void)clearMemory {
[self.memCache removeAllObjects];
}
-- (void)clearDisk
-{
- dispatch_async(self.ioQueue, ^
- {
+- (void)clearDisk {
+ dispatch_async(self.ioQueue, ^{
[[NSFileManager defaultManager] removeItemAtPath:self.diskCachePath error:nil];
[[NSFileManager defaultManager] createDirectoryAtPath:self.diskCachePath
withIntermediateDirectories:YES
@@ -407,13 +345,11 @@ - (void)clearDisk
});
}
-- (void)cleanDisk
-{
- dispatch_async(self.ioQueue, ^
- {
+- (void)cleanDisk {
+ dispatch_async(self.ioQueue, ^{
NSFileManager *fileManager = [NSFileManager defaultManager];
NSURL *diskCacheURL = [NSURL fileURLWithPath:self.diskCachePath isDirectory:YES];
- NSArray *resourceKeys = @[ NSURLIsDirectoryKey, NSURLContentModificationDateKey, NSURLTotalFileAllocatedSizeKey ];
+ NSArray *resourceKeys = @[NSURLIsDirectoryKey, NSURLContentModificationDateKey, NSURLTotalFileAllocatedSizeKey];
// This enumerator prefetches useful properties for our cache files.
NSDirectoryEnumerator *fileEnumerator = [fileManager enumeratorAtURL:diskCacheURL
@@ -429,20 +365,17 @@ - (void)cleanDisk
//
// 1. Removing files that are older than the expiration date.
// 2. Storing file attributes for the size-based cleanup pass.
- for (NSURL *fileURL in fileEnumerator)
- {
+ for (NSURL *fileURL in fileEnumerator) {
NSDictionary *resourceValues = [fileURL resourceValuesForKeys:resourceKeys error:NULL];
// Skip directories.
- if ([resourceValues[NSURLIsDirectoryKey] boolValue])
- {
+ if ([resourceValues[NSURLIsDirectoryKey] boolValue]) {
continue;
}
// Remove files that are older than the expiration date;
NSDate *modificationDate = resourceValues[NSURLContentModificationDateKey];
- if ([[modificationDate laterDate:expirationDate] isEqualToDate:expirationDate])
- {
+ if ([[modificationDate laterDate:expirationDate] isEqualToDate:expirationDate]) {
[fileManager removeItemAtURL:fileURL error:nil];
continue;
}
@@ -455,29 +388,24 @@ - (void)cleanDisk
// If our remaining disk cache exceeds a configured maximum size, perform a second
// size-based cleanup pass. We delete the oldest files first.
- if (self.maxCacheSize > 0 && currentCacheSize > self.maxCacheSize)
- {
+ if (self.maxCacheSize > 0 && currentCacheSize > self.maxCacheSize) {
// Target half of our maximum cache size for this cleanup pass.
const NSUInteger desiredCacheSize = self.maxCacheSize / 2;
// Sort the remaining cache files by their last modification time (oldest first).
NSArray *sortedFiles = [cacheFiles keysSortedByValueWithOptions:NSSortConcurrent
- usingComparator:^NSComparisonResult(id obj1, id obj2)
- {
- return [obj1[NSURLContentModificationDateKey] compare:obj2[NSURLContentModificationDateKey]];
- }];
+ usingComparator:^NSComparisonResult(id obj1, id obj2) {
+ return [obj1[NSURLContentModificationDateKey] compare:obj2[NSURLContentModificationDateKey]];
+ }];
// Delete files until we fall below our desired cache size.
- for (NSURL *fileURL in sortedFiles)
- {
- if ([fileManager removeItemAtURL:fileURL error:nil])
- {
+ for (NSURL *fileURL in sortedFiles) {
+ if ([fileManager removeItemAtURL:fileURL error:nil]) {
NSDictionary *resourceValues = cacheFiles[fileURL];
NSNumber *totalAllocatedSize = resourceValues[NSURLTotalFileAllocatedSizeKey];
currentCacheSize -= [totalAllocatedSize unsignedIntegerValue];
- if (currentCacheSize < desiredCacheSize)
- {
+ if (currentCacheSize < desiredCacheSize) {
break;
}
}
@@ -486,20 +414,17 @@ - (void)cleanDisk
});
}
-- (void)backgroundCleanDisk
-{
+- (void)backgroundCleanDisk {
UIApplication *application = [UIApplication sharedApplication];
- __block UIBackgroundTaskIdentifier bgTask = [application beginBackgroundTaskWithExpirationHandler:^
- {
+ __block UIBackgroundTaskIdentifier bgTask = [application beginBackgroundTaskWithExpirationHandler:^{
// Clean up any unfinished task business by marking where you
// stopped or ending the task outright.
[application endBackgroundTask:bgTask];
bgTask = UIBackgroundTaskInvalid;
}];
// Start the long-running task and return immediately.
- dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^
- {
+ dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// Do the work associated with the task, preferably in chunks.
[self cleanDisk];
@@ -508,58 +433,49 @@ - (void)backgroundCleanDisk
});
}
-- (NSUInteger)getSize
-{
+- (NSUInteger)getSize {
NSUInteger size = 0;
NSDirectoryEnumerator *fileEnumerator = [[NSFileManager defaultManager] enumeratorAtPath:self.diskCachePath];
- for (NSString *fileName in fileEnumerator)
- {
+ for (NSString *fileName in fileEnumerator) {
NSString *filePath = [self.diskCachePath stringByAppendingPathComponent:fileName];
NSDictionary *attrs = [[NSFileManager defaultManager] attributesOfItemAtPath:filePath error:nil];
size += [attrs fileSize];
}
return size;
}
-- (int)getDiskCount
-{
+- (int)getDiskCount {
int count = 0;
NSDirectoryEnumerator *fileEnumerator = [[NSFileManager defaultManager] enumeratorAtPath:self.diskCachePath];
- for (__unused NSString *fileName in fileEnumerator)
- {
+ for (__unused NSString *fileName in fileEnumerator) {
count += 1;
}
return count;
}
-- (void)calculateSizeWithCompletionBlock:(void (^)(NSUInteger fileCount, NSUInteger totalSize))completionBlock
-{
+- (void)calculateSizeWithCompletionBlock:(void (^)(NSUInteger fileCount, NSUInteger totalSize))completionBlock {
NSURL *diskCacheURL = [NSURL fileURLWithPath:self.diskCachePath isDirectory:YES];
- dispatch_async(self.ioQueue, ^
- {
+ dispatch_async(self.ioQueue, ^{
NSUInteger fileCount = 0;
NSUInteger totalSize = 0;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSDirectoryEnumerator *fileEnumerator = [fileManager enumeratorAtURL:diskCacheURL
- includingPropertiesForKeys:@[ NSFileSize ]
+ includingPropertiesForKeys:@[NSFileSize]
options:NSDirectoryEnumerationSkipsHiddenFiles
errorHandler:NULL];
- for (NSURL *fileURL in fileEnumerator)
- {
+ for (NSURL *fileURL in fileEnumerator) {
NSNumber *fileSize;
[fileURL getResourceValue:&fileSize forKey:NSURLFileSizeKey error:NULL];
totalSize += [fileSize unsignedIntegerValue];
fileCount += 1;
}
- if (completionBlock)
- {
- dispatch_main_sync_safe(^
- {
+ if (completionBlock) {
+ dispatch_main_sync_safe(^{
completionBlock(fileCount, totalSize);
});
}
View
18 SDWebImage/SDWebImageCompat.h
@@ -26,7 +26,17 @@
#define UIImageView NSImageView
#endif
#else
+
#import <UIKit/UIKit.h>
+
+#endif
+
+#ifndef NS_ENUM
+#define NS_ENUM(_type, _name) enum _name : _type _name; enum _name : _type
+#endif
+
+#ifndef NS_OPTIONS
+#define NS_OPTIONS(_type, _name) enum _name : _type _name; enum _name : _type
#endif
#if OS_OBJECT_USE_OBJC
@@ -35,10 +45,10 @@
#define SDDispatchQueueRelease(q)
#define SDDispatchQueueSetterSementics strong
#else
- #undef SDDispatchQueueRelease
- #undef SDDispatchQueueSetterSementics
- #define SDDispatchQueueRelease(q) (dispatch_release(q))
- #define SDDispatchQueueSetterSementics assign
+#undef SDDispatchQueueRelease
+#undef SDDispatchQueueSetterSementics
+#define SDDispatchQueueRelease(q) (dispatch_release(q))
+#define SDDispatchQueueSetterSementics assign
#endif
extern UIImage *SDScaledImageForKey(NSString *key, UIImage *image);
View
27 SDWebImage/SDWebImageCompat.m
@@ -12,34 +12,27 @@
#error SDWebImage is ARC only. Either turn on ARC for the project or use -fobjc-arc flag
#endif
-inline UIImage *SDScaledImageForKey(NSString *key, UIImage *image)
-{
- if ([image.images count] > 0)
- {
+inline UIImage *SDScaledImageForKey(NSString *key, UIImage *image) {
+ if ([image.images count] > 0) {
NSMutableArray *scaledImages = [NSMutableArray array];
-
- for (UIImage *tempImage in image.images)
- {
+
+ for (UIImage *tempImage in image.images) {
[scaledImages addObject:SDScaledImageForKey(key, tempImage)];
}
-
+
return [UIImage animatedImageWithImages:scaledImages duration:image.duration];
}
- else
- {
- if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)])
- {
+ else {
+ if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)]) {
CGFloat scale = 1.0;
- if (key.length >= 8)
- {
+ if (key.length >= 8) {
// Search @2x. at the end of the string, before a 3 to 4 extension length (only if key len is 8 or more @2x. + 4 len ext)
NSRange range = [key rangeOfString:@"@2x." options:0 range:NSMakeRange(key.length - 8, 5)];
- if (range.location != NSNotFound)
- {
+ if (range.location != NSNotFound) {
scale = 2.0;
}
}
-
+
UIImage *scaledImage = [[UIImage alloc] initWithCGImage:image.CGImage scale:scale orientation:image.imageOrientation];
image = scaledImage;
}
View
38 SDWebImage/SDWebImageDecoder.m
@@ -12,10 +12,8 @@
@implementation UIImage (ForceDecode)
-+ (UIImage *)decodedImageWithImage:(UIImage *)image
-{
- if (image.images)
- {
++ (UIImage *)decodedImageWithImage:(UIImage *)image {
+ if (image.images) {
// Do not decode animated images
return image;
}
@@ -29,45 +27,43 @@ + (UIImage *)decodedImageWithImage:(UIImage *)image
int infoMask = (bitmapInfo & kCGBitmapAlphaInfoMask);
BOOL anyNonAlpha = (infoMask == kCGImageAlphaNone ||
- infoMask == kCGImageAlphaNoneSkipFirst ||
- infoMask == kCGImageAlphaNoneSkipLast);
+ infoMask == kCGImageAlphaNoneSkipFirst ||
+ infoMask == kCGImageAlphaNoneSkipLast);
// CGBitmapContextCreate doesn't support kCGImageAlphaNone with RGB.
// https://developer.apple.com/library/mac/#qa/qa1037/_index.html
- if (infoMask == kCGImageAlphaNone && CGColorSpaceGetNumberOfComponents(colorSpace) > 1)
- {
+ if (infoMask == kCGImageAlphaNone && CGColorSpaceGetNumberOfComponents(colorSpace) > 1) {
// Unset the old alpha info.
bitmapInfo &= ~kCGBitmapAlphaInfoMask;
-
+
// Set noneSkipFirst.
bitmapInfo |= kCGImageAlphaNoneSkipFirst;
}
- // Some PNGs tell us they have alpha but only 3 components. Odd.
- else if (!anyNonAlpha && CGColorSpaceGetNumberOfComponents(colorSpace) == 3)
- {
+ // Some PNGs tell us they have alpha but only 3 components. Odd.
+ else if (!anyNonAlpha && CGColorSpaceGetNumberOfComponents(colorSpace) == 3) {
// Unset the old alpha info.
bitmapInfo &= ~kCGBitmapAlphaInfoMask;
bitmapInfo |= kCGImageAlphaPremultipliedFirst;
}
// It calculates the bytes-per-row based on the bitsPerComponent and width arguments.
CGContextRef context = CGBitmapContextCreate(NULL,
- imageSize.width,
- imageSize.height,
- CGImageGetBitsPerComponent(imageRef),
- 0,
- colorSpace,
- bitmapInfo);
+ imageSize.width,
+ imageSize.height,
+ CGImageGetBitsPerComponent(imageRef),
+ 0,
+ colorSpace,
+ bitmapInfo);
CGColorSpaceRelease(colorSpace);
// If failed, return undecompressed image
if (!context) return image;
-
+
CGContextDrawImage(context, imageRect, imageRef);
CGImageRef decompressedImageRef = CGBitmapContextCreateImage(context);
-
+
CGContextRelease(context);
-
+
UIImage *decompressedImage = [UIImage imageWithCGImage:decompressedImageRef scale:image.scale orientation:image.imageOrientation];
CGImageRelease(decompressedImageRef);
return decompressedImage;
View
31 SDWebImage/SDWebImageDownloader.h
@@ -10,54 +10,53 @@
#import "SDWebImageCompat.h"
#import "SDWebImageOperation.h"
-typedef enum
-{
+typedef NS_OPTIONS(NSUInteger, SDWebImageDownloaderOptions) {
SDWebImageDownloaderLowPriority = 1 << 0,
SDWebImageDownloaderProgressiveDownload = 1 << 1,
/**
* By default, request prevent the of NSURLCache. With this flag, NSURLCache
* is used with default policies.
*/
- SDWebImageDownloaderUseNSURLCache = 1 << 2,
+ SDWebImageDownloaderUseNSURLCache = 1 << 2,
/**
* Call completion block with nil image/imageData if the image was read from NSURLCache
* (to be combined with `SDWebImageDownloaderUseNSURLCache`).
*/
- SDWebImageDownloaderIgnoreCachedResponse = 1 << 3,
+ SDWebImageDownloaderIgnoreCachedResponse = 1 << 3,
/**
* In iOS 4+, continue the download of the image if the app goes to background. This is achieved by asking the system for
* extra time in background to let the request finish. If the background task expires the operation will be cancelled.
*/
- SDWebImageDownloaderContinueInBackground = 1 << 4,
+ SDWebImageDownloaderContinueInBackground = 1 << 4,
/**
* Handles cookies stored in NSHTTPCookieStore by setting
* NSMutableURLRequest.HTTPShouldHandleCookies = YES;
*/
- SDWebImageDownloaderHandleCookies = 1 << 5,
+ SDWebImageDownloaderHandleCookies = 1 << 5,
/**
* Enable to allow untrusted SSL ceriticates.
* Useful for testing purposes. Use with caution in production.
*/
- SDWebImageDownloaderAllowInvalidSSLCertificates = 1 << 6
+ SDWebImageDownloaderAllowInvalidSSLCertificates = 1 << 6
-} SDWebImageDownloaderOptions;
+};
-typedef enum
-{
+typedef NS_ENUM(NSInteger, SDWebImageDownloaderExecutionOrder) {
SDWebImageDownloaderFIFOExecutionOrder,
/**
* Default value. All download operations will execute in queue style (first-in-first-out).
*/
- SDWebImageDownloaderLIFOExecutionOrder
+ SDWebImageDownloaderLIFOExecutionOrder
/**
* All download operations will execute in stack style (last-in-first-out).
*/
-} SDWebImageDownloaderExecutionOrder;
+};
extern NSString *const SDWebImageDownloadStartNotification;
extern NSString *const SDWebImageDownloadStopNotification;
typedef void(^SDWebImageDownloaderProgressBlock)(NSInteger receivedSize, NSInteger expectedSize);
+
typedef void(^SDWebImageDownloaderCompletedBlock)(UIImage *image, NSData *data, NSError *error, BOOL finished);
/**
@@ -131,9 +130,9 @@ typedef void(^SDWebImageDownloaderCompletedBlock)(UIImage *image, NSData *data,
*
* @return A cancellable SDWebImageOperation
*/
-- (id<SDWebImageOperation>)downloadImageWithURL:(NSURL *)url
- options:(SDWebImageDownloaderOptions)options
- progress:(SDWebImageDownloaderProgressBlock)progressBlock
- completed:(SDWebImageDownloaderCompletedBlock)completedBlock;
+- (id <SDWebImageOperation>)downloadImageWithURL:(NSURL *)url
+ options:(SDWebImageDownloaderOptions)options
+ progress:(SDWebImageDownloaderProgressBlock)progressBlock
+ completed:(SDWebImageDownloaderCompletedBlock)completedBlock;
@end
View
163 SDWebImage/SDWebImageDownloader.m
@@ -29,12 +29,10 @@ @interface SDWebImageDownloader ()
@implementation SDWebImageDownloader
-+ (void)initialize
-{
++ (void)initialize {
// Bind SDNetworkActivityIndicator if available (download it here: http://github.com/rs/SDNetworkActivityIndicator )
// To use it, just add #import "SDNetworkActivityIndicator.h" in addition to the SDWebImage import
- if (NSClassFromString(@"SDNetworkActivityIndicator"))
- {
+ if (NSClassFromString(@"SDNetworkActivityIndicator")) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
@@ -54,126 +52,109 @@ + (void)initialize
}
}
-+ (SDWebImageDownloader *)sharedDownloader
-{
++ (SDWebImageDownloader *)sharedDownloader {
static dispatch_once_t once;
static id instance;
- dispatch_once(&once, ^{instance = self.new;});
+ dispatch_once(&once, ^{
+ instance = [self new];
+ });
return instance;
}
-- (id)init
-{
- if ((self = [super init]))
- {
+- (id)init {
+ if ((self = [super init])) {
_executionOrder = SDWebImageDownloaderFIFOExecutionOrder;
- _downloadQueue = NSOperationQueue.new;
+ _downloadQueue = [NSOperationQueue new];
_downloadQueue.maxConcurrentOperationCount = 2;
- _URLCallbacks = NSMutableDictionary.new;
+ _URLCallbacks = [NSMutableDictionary new];
_HTTPHeaders = [NSMutableDictionary dictionaryWithObject:@"image/webp,image/*;q=0.8" forKey:@"Accept"];
_barrierQueue = dispatch_queue_create("com.hackemist.SDWebImageDownloaderBarrierQueue", DISPATCH_QUEUE_CONCURRENT);
_downloadTimeout = 15.0;
}
return self;
}
-- (void)dealloc
-{
+- (void)dealloc {
[self.downloadQueue cancelAllOperations];
SDDispatchQueueRelease(_barrierQueue);
}
-- (void)setValue:(NSString *)value forHTTPHeaderField:(NSString *)field
-{
- if (value)
- {
+- (void)setValue:(NSString *)value forHTTPHeaderField:(NSString *)field {
+ if (value) {
self.HTTPHeaders[field] = value;
}
- else
- {
+ else {
[self.HTTPHeaders removeObjectForKey:field];
}
}
-- (NSString *)valueForHTTPHeaderField:(NSString *)field
-{
+- (NSString *)valueForHTTPHeaderField:(NSString *)field {
return self.HTTPHeaders[field];
}
-- (void)setMaxConcurrentDownloads:(NSInteger)maxConcurrentDownloads
-{
+- (void)setMaxConcurrentDownloads:(NSInteger)maxConcurrentDownloads {
_downloadQueue.maxConcurrentOperationCount = maxConcurrentDownloads;
}
-- (NSUInteger)currentDownloadCount
-{
+- (NSUInteger)currentDownloadCount {
return _downloadQueue.operationCount;
}
-- (NSInteger)maxConcurrentDownloads
-{
+- (NSInteger)maxConcurrentDownloads {
return _downloadQueue.maxConcurrentOperationCount;
}
-- (id<SDWebImageOperation>)downloadImageWithURL:(NSURL *)url options:(SDWebImageDownloaderOptions)options progress:(void (^)(NSInteger, NSInteger))progressBlock completed:(void (^)(UIImage *, NSData *, NSError *, BOOL))completedBlock
-{
+- (id <SDWebImageOperation>)downloadImageWithURL:(NSURL *)url options:(SDWebImageDownloaderOptions)options progress:(void (^)(NSInteger, NSInteger))progressBlock completed:(void (^)(UIImage *, NSData *, NSError *, BOOL))completedBlock {
__block SDWebImageDownloaderOperation *operation;
__weak SDWebImageDownloader *wself = self;
- [self addProgressCallback:progressBlock andCompletedBlock:completedBlock forURL:url createCallback:^
- {
+ [self addProgressCallback:progressBlock andCompletedBlock:completedBlock forURL:url createCallback:^{
NSTimeInterval timeoutInterval = wself.downloadTimeout;
if (timeoutInterval == 0.0) {
timeoutInterval = 15.0;
}
-
+
// In order to prevent from potential duplicate caching (NSURLCache + SDImageCache) we disable the cache for image requests if told otherwise
- NSMutableURLRequest *request = [NSMutableURLRequest.alloc initWithURL:url cachePolicy:(options & SDWebImageDownloaderUseNSURLCache ? NSURLRequestUseProtocolCachePolicy : NSURLRequestReloadIgnoringLocalCacheData) timeoutInterval:timeoutInterval];
+ NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url cachePolicy:(options & SDWebImageDownloaderUseNSURLCache ? NSURLRequestUseProtocolCachePolicy : NSURLRequestReloadIgnoringLocalCacheData) timeoutInterval:timeoutInterval];
request.HTTPShouldHandleCookies = (options & SDWebImageDownloaderHandleCookies);
request.HTTPShouldUsePipelining = YES;
- if (wself.headersFilter)
- {
+ if (wself.headersFilter) {
request.allHTTPHeaderFields = wself.headersFilter(url, [wself.HTTPHeaders copy]);
}
- else
- {
+ else {
request.allHTTPHeaderFields = wself.HTTPHeaders;
}
- operation = [SDWebImageDownloaderOperation.alloc initWithRequest:request options:options progress:^(NSInteger receivedSize, NSInteger expectedSize)
- {
- if (!wself) return;
- SDWebImageDownloader *sself = wself;
- NSArray *callbacksForURL = [sself callbacksForURL:url];
- for (NSDictionary *callbacks in callbacksForURL)
- {
- SDWebImageDownloaderProgressBlock callback = callbacks[kProgressCallbackKey];
- if (callback) callback(receivedSize, expectedSize);
- }
- }
- completed:^(UIImage *image, NSData *data, NSError *error, BOOL finished)
- {
- if (!wself) return;
- SDWebImageDownloader *sself = wself;
- NSArray *callbacksForURL = [sself callbacksForURL:url];
- if (finished)
- {
- [sself removeCallbacksForURL:url];
- }
- for (NSDictionary *callbacks in callbacksForURL)
- {
- SDWebImageDownloaderCompletedBlock callback = callbacks[kCompletedCallbackKey];
- if (callback) callback(image, data, error, finished);
- }
- }
- cancelled:^
- {
- if (!wself) return;
- SDWebImageDownloader *sself = wself;
- [sself removeCallbacksForURL:url];
- }];
+ operation = [[SDWebImageDownloaderOperation alloc] initWithRequest:request
+ options:options
+ progress:^(NSInteger receivedSize, NSInteger expectedSize) {
+ if (!wself) return;
+ SDWebImageDownloader *sself = wself;
+ NSArray *callbacksForURL = [sself callbacksForURL:url];
+ for (NSDictionary *callbacks in callbacksForURL) {
+ SDWebImageDownloaderProgressBlock callback = callbacks[kProgressCallbackKey];
+ if (callback) callback(receivedSize, expectedSize);
+ }
+ }
+ completed:^(UIImage *image, NSData *data, NSError *error, BOOL finished) {
+ if (!wself) return;
+ SDWebImageDownloader *sself = wself;
+ NSArray *callbacksForURL = [sself callbacksForURL:url];
+ if (finished) {
+ [sself removeCallbacksForURL:url];
+ }
+ for (NSDictionary *callbacks in callbacksForURL) {
+ SDWebImageDownloaderCompletedBlock callback = callbacks[kCompletedCallbackKey];
+ if (callback) callback(image, data, error, finished);
+ }
+ }
+ cancelled:^{
+ if (!wself) return;
+ SDWebImageDownloader *sself = wself;
+ [sself removeCallbacksForURL:url];
+ }];
+
[wself.downloadQueue addOperation:operation];
- if (wself.executionOrder == SDWebImageDownloaderLIFOExecutionOrder)
- {
+ if (wself.executionOrder == SDWebImageDownloaderLIFOExecutionOrder) {
// Emulate LIFO execution order by systematically adding new operations as last operation's dependency
[wself.lastAddedOperation addDependency:operation];
wself.lastAddedOperation = operation;
@@ -183,56 +164,46 @@ - (NSInteger)maxConcurrentDownloads
return operation;
}
-- (void)addProgressCallback:(void (^)(NSInteger, NSInteger))progressBlock andCompletedBlock:(void (^)(UIImage *, NSData *data, NSError *, BOOL))completedBlock forURL:(NSURL *)url createCallback:(void (^)())createCallback
-{
+- (void)addProgressCallback:(void (^)(NSInteger, NSInteger))progressBlock andCompletedBlock:(void (^)(UIImage *, NSData *data, NSError *, BOOL))completedBlock forURL:(NSURL *)url createCallback:(void (^)())createCallback {
// The URL will be used as the key to the callbacks dictionary so it cannot be nil. If it is nil immediately call the completed block with no image or data.
- if(url == nil)
- {
- if (completedBlock != nil)
- {
+ if (url == nil) {
+ if (completedBlock != nil) {
completedBlock(nil, nil, nil, NO);
}
return;
}
-
- dispatch_barrier_sync(self.barrierQueue, ^
- {
+
+ dispatch_barrier_sync(self.barrierQueue, ^{
BOOL first = NO;
- if (!self.URLCallbacks[url])
- {
- self.URLCallbacks[url] = NSMutableArray.new;
+ if (!self.URLCallbacks[url]) {
+ self.URLCallbacks[url] = [NSMutableArray new];
first = YES;
}
// Handle single download of simultaneous download request for the same URL
NSMutableArray *callbacksForURL = self.URLCallbacks[url];
- NSMutableDictionary *callbacks = NSMutableDictionary.new;
+ NSMutableDictionary *callbacks = [NSMutableDictionary new];
if (progressBlock) callbacks[kProgressCallbackKey] = [progressBlock copy];
if (completedBlock) callbacks[kCompletedCallbackKey] = [completedBlock copy];
[callbacksForURL addObject:callbacks];
self.URLCallbacks[url] = callbacksForURL;
- if (first)
- {
+ if (first) {
createCallback();
}
});
}
-- (NSArray *)callbacksForURL:(NSURL *)url
-{
+- (NSArray *)callbacksForURL:(NSURL *)url {
__block NSArray *callbacksForURL;
- dispatch_sync(self.barrierQueue, ^
- {
+ dispatch_sync(self.barrierQueue, ^{
callbacksForURL = self.URLCallbacks[url];
});
return [callbacksForURL copy];
}
-- (void)removeCallbacksForURL:(NSURL *)url
-{
- dispatch_barrier_async(self.barrierQueue, ^
- {
+- (void)removeCallbacksForURL:(NSURL *)url {
+ dispatch_barrier_async(self.barrierQueue, ^{
[self.URLCallbacks removeObjectForKey:url];
});
}
View
202 SDWebImage/SDWebImageDownloaderOperation.m
@@ -30,16 +30,13 @@ @interface SDWebImageDownloaderOperation ()
@end
-@implementation SDWebImageDownloaderOperation
-{
+@implementation SDWebImageDownloaderOperation {
size_t width, height;
BOOL responseFromCached;
}
-- (id)initWithRequest:(NSURLRequest *)request options:(SDWebImageDownloaderOptions)options progress:(void (^)(NSInteger, NSInteger))progressBlock completed:(void (^)(UIImage *, NSData *, NSError *, BOOL))completedBlock cancelled:(void (^)())cancelBlock
-{
- if ((self = [super init]))
- {
+- (id)initWithRequest:(NSURLRequest *)request options:(SDWebImageDownloaderOptions)options progress:(void (^)(NSInteger, NSInteger))progressBlock completed:(void (^)(UIImage *, NSData *, NSError *, BOOL))completedBlock cancelled:(void (^)())cancelBlock {
+ if ((self = [super init])) {
_request = request;
_options = options;
_progressBlock = [progressBlock copy];
@@ -53,27 +50,21 @@ - (id)initWithRequest:(NSURLRequest *)request options:(SDWebImageDownloaderOptio
return self;
}
-- (void)start
-{
- @synchronized(self)
- {
- if (self.isCancelled)
- {
+- (void)start {
+ @synchronized (self) {
+ if (self.isCancelled) {
self.finished = YES;
[self reset];
return;
}
#if TARGET_OS_IPHONE && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_4_0
- if ([self shouldContinueWhenAppEntersBackground])
- {
- __weak __typeof__(self) wself = self;
- self.backgroundTaskId = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^
- {
- __strong __typeof(wself)sself = wself;
+ if ([self shouldContinueWhenAppEntersBackground]) {
+ __weak __typeof__ (self) wself = self;
+ self.backgroundTaskId = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
+ __strong __typeof (wself) sself = wself;
- if (sself)
- {
+ if (sself) {
[sself cancel];
[[UIApplication sharedApplication] endBackgroundTask:sself.backgroundTaskId];
@@ -84,76 +75,62 @@ - (void)start
#endif
self.executing = YES;
- self.connection = [NSURLConnection.alloc initWithRequest:self.request delegate:self startImmediately:NO];
+ self.connection = [[NSURLConnection alloc] initWithRequest:self.request delegate:self startImmediately:NO];
self.thread = [NSThread currentThread];
}
[self.connection start];
- if (self.connection)
- {
- if (self.progressBlock)
- {
+ if (self.connection) {
+ if (self.progressBlock) {
self.progressBlock(0, NSURLResponseUnknownLength);
}
[[NSNotificationCenter defaultCenter] postNotificationName:SDWebImageDownloadStartNotification object:self];
- if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_5_1)
- {
+ if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_5_1) {
// Make sure to run the runloop in our background thread so it can process downloaded data
// Note: we use a timeout to work around an issue with NSURLConnection cancel under iOS 5
// not waking up the runloop, leading to dead threads (see https://github.com/rs/SDWebImage/issues/466)
CFRunLoopRunInMode(kCFRunLoopDefaultMode, 10, false);
}
- else
- {
+ else {
CFRunLoopRun();
}
- if (!self.isFinished)
- {
+ if (!self.isFinished) {
[self.connection cancel];
- [self connection:self.connection didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorTimedOut userInfo:@{NSURLErrorFailingURLErrorKey: self.request.URL}]];
+ [self connection:self.connection didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorTimedOut userInfo:@{NSURLErrorFailingURLErrorKey : self.request.URL}]];
}
}
- else
- {
- if (self.completedBlock)
- {
- self.completedBlock(nil, nil, [NSError errorWithDomain:NSURLErrorDomain code:0 userInfo:@{NSLocalizedDescriptionKey: @"Connection can't be initialized"}], YES);
+ else {
+ if (self.completedBlock) {
+ self.completedBlock(nil, nil, [NSError errorWithDomain:NSURLErrorDomain code:0 userInfo:@{NSLocalizedDescriptionKey : @"Connection can't be initialized"}], YES);
}
}
}
-- (void)cancel
-{
- @synchronized(self)
- {
- if (self.thread)
- {
+- (void)cancel {
+ @synchronized (self) {
+ if (self.thread) {
[self performSelector:@selector(cancelInternalAndStop) onThread:self.thread withObject:nil waitUntilDone:NO];
}
- else
- {
+ else {
[self cancelInternal];
}
}
}
-- (void)cancelInternalAndStop
-{
+- (void)cancelInternalAndStop {
[self cancelInternal];
CFRunLoopStop(CFRunLoopGetCurrent());
}
-- (void)cancelInternal
-{
+- (void)cancelInternal {
if (self.isFinished) return;
[super cancel];
if (self.cancelBlock) self.cancelBlock();
- if (self.connection)
- {
+ if (self.connection) {
[self.connection cancel];
[[NSNotificationCenter defaultCenter] postNotificationName:SDWebImageDownloadStopNotification object:self];
@@ -166,15 +143,13 @@ - (void)cancelInternal
[self reset];
}
-- (void)done
-{
+- (void)done {
self.finished = YES;
self.executing = NO;
[self reset];
}
-- (void)reset
-{
+- (void)reset {
self.cancelBlock = nil;
self.completedBlock = nil;
self.progressBlock = nil;
@@ -183,61 +158,51 @@ - (void)reset
self.thread = nil;
}
-- (void)setFinished:(BOOL)finished
-{
+- (void)setFinished:(BOOL)finished {
[self willChangeValueForKey:@"isFinished"];
_finished = finished;
[self didChangeValueForKey:@"isFinished"];
}
-- (void)setExecuting:(BOOL)executing
-{
+- (void)setExecuting:(BOOL)executing {
[self willChangeValueForKey:@"isExecuting"];
_executing = executing;
[self didChangeValueForKey:@"isExecuting"];
}
-- (BOOL)isConcurrent
-{
+- (BOOL)isConcurrent {
return YES;
}
#pragma mark NSURLConnection (delegate)
-- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
-{
- if (![response respondsToSelector:@selector(statusCode)] || [((NSHTTPURLResponse *)response) statusCode] < 400)
- {
+- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
+ if (![response respondsToSelector:@selector(statusCode)] || [((NSHTTPURLResponse *)response) statusCode] < 400) {
NSInteger expected = response.expectedContentLength > 0 ? (NSInteger)response.expectedContentLength : 0;
self.expectedSize = expected;
- if (self.progressBlock)
- {
+ if (self.progressBlock) {
self.progressBlock(0, expected);
}
- self.imageData = [NSMutableData.alloc initWithCapacity:expected];
+ self.imageData = [[NSMutableData alloc] initWithCapacity:expected];
}
- else
- {
+ else {
[self.connection cancel];
[[NSNotificationCenter defaultCenter] postNotificationName:SDWebImageDownloadStopNotification object:nil];
- if (self.completedBlock)
- {
+ if (self.completedBlock) {
self.completedBlock(nil, nil, [NSError errorWithDomain:NSURLErrorDomain code:[((NSHTTPURLResponse *)response) statusCode] userInfo:nil], YES);
}
[self done];
}
}
-- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
-{
+- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[self.imageData appendData:data];
- if ((self.options & SDWebImageDownloaderProgressiveDownload) && self.expectedSize > 0 && self.completedBlock)
- {
+ if ((self.options & SDWebImageDownloaderProgressiveDownload) && self.expectedSize > 0 && self.completedBlock) {
// The following code is from http://www.cocoaintheshell.com/2011/05/progressive-images-download-imageio/
// Thanks to the author @Nyx0uf
@@ -246,13 +211,11 @@ - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
// Update the data source, we must pass ALL the data, not just the new bytes
CGImageSourceRef imageSource = CGImageSourceCreateIncremental(NULL);
- CGImageSourceUpdateData(imageSource, (__bridge CFDataRef)self.imageData, totalSize == self.expectedSize);
+ CGImageSourceUpdateData(imageSource, (__bridge CFDataRef)self.imageData, totalSize == self.expectedSize);
- if (width + height == 0)
- {
+ if (width + height == 0) {
CFDictionaryRef properties = CGImageSourceCopyPropertiesAtIndex(imageSource, 0, NULL);
- if (properties)
- {
+ if (properties) {
CFTypeRef val = CFDictionaryGetValue(properties, kCGImagePropertyPixelHeight);
if (val) CFNumberGetValue(val, kCFNumberLongType, &height);
val = CFDictionaryGetValue(properties, kCGImagePropertyPixelWidth);
@@ -261,44 +224,37 @@ - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
}
}
- if (width + height > 0 && totalSize < self.expectedSize)
- {
+ if (width + height > 0 && totalSize < self.expectedSize) {
// Create the image
CGImageRef partialImageRef = CGImageSourceCreateImageAtIndex(imageSource, 0, NULL);
#ifdef TARGET_OS_IPHONE
// Workaround for iOS anamorphic image
- if (partialImageRef)
- {
+ if (partialImageRef) {
const size_t partialHeight = CGImageGetHeight(partialImageRef);
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef bmContext = CGBitmapContextCreate(NULL, width, height, 8, width * 4, colorSpace, kCGBitmapByteOrderDefault | kCGImageAlphaPremultipliedFirst);
CGColorSpaceRelease(colorSpace);
- if (bmContext)
- {
+ if (bmContext) {
CGContextDrawImage(bmContext, (CGRect){.origin.x = 0.0f, .origin.y = 0.0f, .size.width = width, .size.height = partialHeight}, partialImageRef);
CGImageRelease(partialImageRef);
partialImageRef = CGBitmapContextCreateImage(bmContext);
CGContextRelease(bmContext);
}
- else
- {
+ else {
CGImageRelease(partialImageRef);
partialImageRef = nil;
}
}
#endif
- if (partialImageRef)
- {
+ if (partialImageRef) {
UIImage *image = [UIImage imageWithCGImage:partialImageRef];
UIImage *scaledImage = [self scaledImageForKey:self.request.URL.absoluteString image:image];
image = [UIImage decodedImageWithImage:scaledImage];
CGImageRelease(partialImageRef);
- dispatch_main_sync_safe(^
- {
- if (self.completedBlock)
- {
+ dispatch_main_sync_safe(^{
+ if (self.completedBlock) {
self.completedBlock(image, nil, nil, NO);
}
});
@@ -308,36 +264,30 @@ - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
CFRelease(imageSource);
}
- if (self.progressBlock)
- {
+ if (self.progressBlock) {
self.progressBlock(self.imageData.length, self.expectedSize);
}
}
-- (UIImage *)scaledImageForKey:(NSString *)key image:(UIImage *)image
-{
+- (UIImage *)scaledImageForKey:(NSString *)key image:(UIImage *)image {
return SDScaledImageForKey(key, image);
}
-- (void)connectionDidFinishLoading:(NSURLConnection *)aConnection
-{
+- (void)connectionDidFinishLoading:(NSURLConnection *)aConnection {
CFRunLoopStop(CFRunLoopGetCurrent());
self.connection = nil;
[[NSNotificationCenter defaultCenter] postNotificationName:SDWebImageDownloadStopNotification object:nil];
SDWebImageDownloaderCompletedBlock completionBlock = self.completedBlock;
- if (completionBlock)
- {
- if (self.options & SDWebImageDownloaderIgnoreCachedResponse && responseFromCached)
- {
+ if (completionBlock) {
+ if (self.options & SDWebImageDownloaderIgnoreCachedResponse && responseFromCached) {
completionBlock(nil, nil, nil, YES);
self.completionBlock = nil;
[self done];
}
- else
- {
+ else {
UIImage *image = [UIImage sd_imageWithData:self.imageData];
@@ -348,66 +298,54 @@ - (void)connectionDidFinishLoading:(NSURLConnection *)aConnection
image = [UIImage decodedImageWithImage:image];
}
- if (CGSizeEqualToSize(image.size, CGSizeZero))
- {
- completionBlock(nil, nil, [NSError errorWithDomain:@"SDWebImageErrorDomain" code:0 userInfo:@{NSLocalizedDescriptionKey: @"Downloaded image has 0 pixels"}], YES);
+ if (CGSizeEqualToSize(image.size, CGSizeZero)) {
+ completionBlock(nil, nil, [NSError errorWithDomain:@"SDWebImageErrorDomain" code:0 userInfo:@{NSLocalizedDescriptionKey : @"Downloaded image has 0 pixels"}], YES);
}
- else
- {
+ else {
completionBlock(image, self.imageData, nil, YES);
}
self.completionBlock = nil;
[self done];
}
}
- else
- {
+ else {
[self done];
}
}
-- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
-{
+- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
CFRunLoopStop(CFRunLoopGetCurrent());
[[NSNotificationCenter defaultCenter] postNotificationName:SDWebImageDownloadStopNotification object:nil];
- if (self.completedBlock)
- {
+ if (self.completedBlock) {
self.completedBlock(nil, nil, error, YES);
}
[self done];
}
-- (NSCachedURLResponse *)connection:(NSURLConnection *)connection willCacheResponse:(NSCachedURLResponse *)cachedResponse
-{
+- (NSCachedURLResponse *)connection:(NSURLConnection *)connection willCacheResponse:(NSCachedURLResponse *)cachedResponse {
responseFromCached = NO; // If this method is called, it means the response wasn't read from cache
- if (self.request.cachePolicy == NSURLRequestReloadIgnoringLocalCacheData)
- {
+ if (self.request.cachePolicy == NSURLRequestReloadIgnoringLocalCacheData) {
// Prevents caching of responses
return nil;
}
- else
- {
+ else {
return cachedResponse;
}
}
-- (BOOL)shouldContinueWhenAppEntersBackground
-{
+- (BOOL)shouldContinueWhenAppEntersBackground {
return self.options & SDWebImageDownloaderContinueInBackground;
}
-- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace
-{
+- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace {
return [protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust];
}
-- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
-{
+- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
BOOL trustAllCertificates = (self.options & SDWebImageDownloaderAllowInvalidSSLCertificates);
- if (trustAllCertificates && [challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust])
- {
+ if (trustAllCertificates && [challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
[challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]
forAuthenticationChallenge:challenge];
}
View
32 SDWebImage/SDWebImageManager.h
@@ -11,27 +11,26 @@
#import "SDWebImageDownloader.h"
#import "SDImageCache.h"
-typedef enum
-{
+typedef NS_OPTIONS(NSUInteger, SDWebImageOptions) {
/**
* By default, when a URL fail to be downloaded, the URL is blacklisted so the library won't keep trying.
* This flag disable this blacklisting.
*/
- SDWebImageRetryFailed = 1 << 0,
+ SDWebImageRetryFailed = 1 << 0,
/**
* By default, image downloads are started during UI interactions, this flags disable this feature,
* leading to delayed download on UIScrollView deceleration for instance.
*/
- SDWebImageLowPriority = 1 << 1,
+ SDWebImageLowPriority = 1 << 1,
/**
* This flag disables on-disk caching
*/
- SDWebImageCacheMemoryOnly = 1 << 2,
+ SDWebImageCacheMemoryOnly = 1 << 2,
/**
* This flag enables progressive download, the image is displayed progressively during download as a browser would do.
* By default, the image is only displayed once completely downloaded.
*/
- SDWebImageProgressiveDownload = 1 << 3,
+ SDWebImageProgressiveDownload = 1 << 3,
/**
* Even if the image is cached, respect the HTTP response cache control, and refresh the image from remote location if needed.
* The disk caching will be handled by NSURLCache instead of SDWebImage leading to slight performance degradation.
@@ -40,26 +39,27 @@ typedef enum
*
* Use this flag only if you can't make your URLs static with embeded cache busting parameter.
*/
- SDWebImageRefreshCached = 1 << 4,
+ SDWebImageRefreshCached = 1 << 4,
/**
* In iOS 4+, continue the download of the image if the app goes to background. This is achieved by asking the system for
* extra time in background to let the request finish. If the background task expires the operation will be cancelled.
*/
- SDWebImageContinueInBackground = 1 << 5,
+ SDWebImageContinueInBackground = 1 << 5,
/**
* Handles cookies stored in NSHTTPCookieStore by setting
* NSMutableURLRequest.HTTPShouldHandleCookies = YES;
*/
- SDWebImageHandleCookies = 1 << 6,
+ SDWebImageHandleCookies = 1 << 6,
/**
* Enable to allow untrusted SSL ceriticates.
* Useful for testing purposes. Use with caution in production.
*/
- SDWebImageAllowInvalidSSLCertificates = 1 << 7
-} SDWebImageOptions;
+ SDWebImageAllowInvalidSSLCertificates = 1 << 7
+};
typedef void(^SDWebImageCompletedBlock)(UIImage *image, NSError *error, SDImageCacheType cacheType);
+
typedef void(^SDWebImageCompletedWithFinishedBlock)(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished);
@@ -119,7 +119,7 @@ SDWebImageManager *manager = [SDWebImageManager sharedManager];
*/
@interface SDWebImageManager : NSObject
-@property (weak, nonatomic) id<SDWebImageManagerDelegate> delegate;
+@property (weak, nonatomic) id <SDWebImageManagerDelegate> delegate;
@property (strong, nonatomic, readonly) SDImageCache *imageCache;
@property (strong, nonatomic, readonly) SDWebImageDownloader *imageDownloader;
@@ -172,10 +172,10 @@ SDWebImageManager *manager = [SDWebImageManager sharedManager];
*
* @return Returns a cancellable NSOperation
*/
-- (id<SDWebImageOperation>)downloadWithURL:(NSURL *)url
- options:(SDWebImageOptions)options
- progress:(SDWebImageDownloaderProgressBlock)progressBlock
- completed:(SDWebImageCompletedWithFinishedBlock)completedBlock;
+- (id <SDWebImageOperation>)downloadWithURL:(NSURL *)url
+ options:(SDWebImageOptions)options
+ progress:(SDWebImageDownloaderProgressBlock)progressBlock
+ completed:(SDWebImageCompletedWithFinishedBlock)completedBlock;
/**
* Cancel all current opreations
View
192 SDWebImage/SDWebImageManager.m
@@ -7,7 +7,6 @@
*/
#import "SDWebImageManager.h"
-#import "UIImage+GIF.h"
#import <objc/message.h>
@interface SDWebImageCombinedOperation : NSObject <SDWebImageOperation>
@@ -29,110 +28,91 @@ @interface SDWebImageManager ()
@implementation SDWebImageManager
-+ (id)sharedManager
-{
++ (id)sharedManager {
static dispatch_once_t once;
static id instance;
- dispatch_once(&once, ^{instance = self.new;});
+ dispatch_once(&once, ^{
+ instance = [self new];
+ });
return instance;
}
-- (id)init
-{
- if ((self = [super init]))
- {
+- (id)init {
+ if ((self = [super init])) {
_imageCache = [self createCache];
- _imageDownloader = SDWebImageDownloader.new;
- _failedURLs = NSMutableArray.new;
- _runningOperations = NSMutableArray.new;
+ _imageDownloader = [SDWebImageDownloader new];
+ _failedURLs = [NSMutableArray new];
+ _runningOperations = [NSMutableArray new];
}
return self;
}
-- (SDImageCache *)createCache
-{
+- (SDImageCache *)createCache {
return [SDImageCache sharedImageCache];
}
-- (NSString *)cacheKeyForURL:(NSURL *)url
-{
- if (self.cacheKeyFilter)
- {
+- (NSString *)cacheKeyForURL:(NSURL *)url {
+ if (self.cacheKeyFilter) {
return self.cacheKeyFilter(url);
}
- else
- {
+ else {
return [url absoluteString];
}
}
-- (BOOL)diskImageExistsForURL:(NSURL *)url
-{
+- (BOOL)diskImageExistsForURL:(NSURL *)url {
NSString *key = [self cacheKeyForURL:url];
return [self.imageCache diskImageExistsWithKey:key];
}
-- (id<SDWebImageOperation>)downloadWithURL:(NSURL *)url options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletedWithFinishedBlock)completedBlock
-{
+- (id <SDWebImageOperation>)downloadWithURL:(NSURL *)url options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletedWithFinishedBlock)completedBlock {
// Invoking this method without a completedBlock is pointless
NSParameterAssert(completedBlock);
-
+
// Very common mistake is to send the URL using NSString object instead of NSURL. For some strange reason, XCode won't
// throw any warning for this type mismatch. Here we failsafe this error by allowing URLs to be passed as NSString.
- if ([url isKindOfClass:NSString.class])
- {
+ if ([url isKindOfClass:NSString.class]) {
url = [NSURL URLWithString:(NSString *)url];
}
// Prevents app crashing on argument type error like sending NSNull instead of NSURL
- if (![url isKindOfClass:NSURL.class])
- {
+ if (![url isKindOfClass:NSURL.class]) {
url = nil;
}
- __block SDWebImageCombinedOperation *operation = SDWebImageCombinedOperation.new;
+ __block SDWebImageCombinedOperation *operation = [SDWebImageCombinedOperation new];
__weak SDWebImageCombinedOperation *weakOperation = operation;
-
+
BOOL isFailedUrl = NO;
- @synchronized(self.failedURLs)
- {
+ @synchronized (self.failedURLs) {
isFailedUrl = [self.failedURLs containsObject:url];
}
- if (!url || (!(options & SDWebImageRetryFailed) && isFailedUrl))
- {
- dispatch_main_sync_safe(^
- {
- NSError *error = [NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil];
- completedBlock(nil, error, SDImageCacheTypeNone, YES);
+ if (!url || (!(options & SDWebImageRetryFailed) && isFailedUrl)) {
+ dispatch_main_sync_safe(^{
+ NSError *error = [NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil];
+ completedBlock(nil, error, SDImageCacheTypeNone, YES);
});
return operation;
}
- @synchronized(self.runningOperations)
- {
+ @synchronized (self.runningOperations) {
[self.runningOperations addObject:operation];
}
NSString *key = [self cacheKeyForURL:url];
- operation.cacheOperation = [self.imageCache queryDiskCacheForKey:key done:^(UIImage *image, SDImageCacheType cacheType)
- {
- if (operation.isCancelled)
- {
- @synchronized(self.runningOperations)
- {
+ operation.cacheOperation = [self.imageCache queryDiskCacheForKey:key done:^(UIImage *image, SDImageCacheType cacheType) {
+ if (operation.isCancelled) {
+ @synchronized (self.runningOperations) {
[self.runningOperations removeObject:operation];
}
return;
}
- if ((!image || options & SDWebImageRefreshCached) && (![self.delegate respondsToSelector:@selector(imageManager:shouldDownloadImageForURL:)] || [self.delegate imageManager:self shouldDownloadImageForURL:url]))
- {
- if (image && options & SDWebImageRefreshCached)
- {
- dispatch_main_sync_safe(^
- {
+ if ((!image || options & SDWebImageRefreshCached) && (![self.delegate respondsToSelector:@selector(imageManager:shouldDownloadImageForURL:)] || [self.delegate imageManager:self shouldDownloadImageForURL:url])) {
+ if (image && options & SDWebImageRefreshCached) {
+ dispatch_main_sync_safe(^{
// If image was found in the cache bug SDWebImageRefreshCached is provided, notify about the cached image
// AND try to re-download it in order to let a chance to NSURLCache to refresh it from server.
completedBlock(image, nil, cacheType, YES);
@@ -147,108 +127,85 @@ - (BOOL)diskImageExistsForURL:(NSURL *)url
if (options & SDWebImageContinueInBackground) downloaderOptions |= SDWebImageDownloaderContinueInBackground;
if (options & SDWebImageHandleCookies) downloaderOptions |= SDWebImageDownloaderHandleCookies;
if (options & SDWebImageAllowInvalidSSLCertificates) downloaderOptions |= SDWebImageDownloaderAllowInvalidSSLCertificates;
- if (image && options & SDWebImageRefreshCached)
- {
+ if (image && options & SDWebImageRefreshCached) {
// force progressive off if image already cached but forced refreshing
downloaderOptions &= ~SDWebImageDownloaderProgressiveDownload;
// ignore image read from NSURLCache if image if cached but force refreshing
downloaderOptions |= SDWebImageDownloaderIgnoreCachedResponse;
}
- id<SDWebImageOperation> subOperation = [self.imageDownloader downloadImageWithURL:url options:downloaderOptions progress:progressBlock completed:^(UIImage *downloadedImage, NSData *data, NSError *error, BOOL finished)
- {
- if (weakOperation.isCancelled)
- {
- dispatch_main_sync_safe(^
- {
+ id <SDWebImageOperation> subOperation = [self.imageDownloader downloadImageWithURL:url options:downloaderOptions progress:progressBlock completed:^(UIImage *downloadedImage, NSData *data, NSError *error, BOOL finished) {
+ if (weakOperation.isCancelled) {
+ dispatch_main_sync_safe(^{
completedBlock(nil, nil, SDImageCacheTypeNone, finished);
});
}
- else if (error)
- {
- dispatch_main_sync_safe(^
- {
+ else if (error) {
+ dispatch_main_sync_safe(^{
completedBlock(nil, error, SDImageCacheTypeNone, finished);
});
- if (error.code != NSURLErrorNotConnectedToInternet)
- {
- @synchronized(self.failedURLs)
- {
+ if (error.code != NSURLErrorNotConnectedToInternet) {
+ @synchronized (self.failedURLs) {
[self.failedURLs addObject:url];
}
}
}
- else
- {
+ else {
BOOL cacheOnDisk = !(options & SDWebImageCacheMemoryOnly);
- if (options & SDWebImageRefreshCached && image && !downloadedImage)
- {
+ if (options & SDWebImageRefreshCached && image && !downloadedImage) {
// Image refresh hit the NSURLCache cache, do not call the completion block
}
- // NOTE: We don't call transformDownloadedImage delegate method on animated images as most transformation code would mangle it
- else if (downloadedImage && !downloadedImage.images && [self.delegate respondsToSelector:@selector(imageManager:transformDownloadedImage:withURL:)])
- {
- dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^
- {
+ // NOTE: We don't call transformDownloadedImage delegate method on animated images as most transformation code would mangle it
+ else if (downloadedImage && !downloadedImage.images && [self.delegate respondsToSelector:@selector(imageManager:transformDownloadedImage:withURL:)]) {
+ dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
UIImage *transformedImage = [self.delegate imageManager:self transformDownloadedImage:downloadedImage withURL:url];
- dispatch_main_sync_safe(^
- {
+ dispatch_main_sync_safe(^{
completedBlock(transformedImage, nil, SDImageCacheTypeNone, finished);
});
- if (transformedImage && finished)
- {
+ if (transformedImage && finished) {
BOOL imageWasTransformed = ![transformedImage isEqual:downloadedImage];
[self.imageCache storeImage:transformedImage recalculateFromImage:imageWasTransformed imageData:data forKey:key toDisk:cacheOnDisk];
}
});
}
- else
- {
- dispatch_main_sync_safe(^
- {
+ else {
+ dispatch_main_sync_safe(^{
completedBlock(downloadedImage, nil, SDImageCacheTypeNone, finished);
});
- if (downloadedImage && finished)
- {
+ if (downloadedImage && finished) {
[self.imageCache storeImage:downloadedImage recalculateFromImage:NO imageData:data forKey:key toDisk:cacheOnDisk];
}
}
}
- if (finished)
- {
- @synchronized(self.runningOperations)
- {
+ if (finished) {
+ @synchronized (self.runningOperations) {
[self.runningOperations removeObject:operation];
}
}
}];
- operation.cancelBlock = ^{[subOperation cancel];};
+ operation.cancelBlock = ^{
+ [subOperation cancel];
+ };
}
- else if (image)
- {
- dispatch_main_sync_safe(^
- {
+ else if (image) {
+ dispatch_main_sync_safe(^{
completedBlock(image, nil, cacheType, YES);
});
- @synchronized(self.runningOperations)
- {
+ @synchronized (self.runningOperations) {
[self.runningOperations removeObject:operation];
}
}
- else
- {
+ else {
// Image not in cache and download disallowed by delegate
- dispatch_main_sync_safe(^
- {
+ dispatch_main_sync_safe(^{
completedBlock(nil, nil, SDImageCacheTypeNone, YES);
});
- @synchronized(self.runningOperations)
- {
+ @synchronized (self.runningOperations) {
[self.runningOperations removeObject:operation];
}
}
@@ -257,46 +214,37 @@ - (BOOL)diskImageExistsForURL:(NSURL *)url
return operation;
}
-- (void)cancelAll
-{
- @synchronized(self.runningOperations)
- {
+- (void)cancelAll {
+ @synchronized (self.runningOperations) {
[self.runningOperations makeObjectsPerformSelector:@selector(cancel)];
[self.runningOperations removeAllObjects];
}
}
-- (BOOL)isRunning
-{
+- (BOOL)isRunning {
return self.runningOperations.count > 0;
}
@end
@implementation SDWebImageCombinedOperation
-- (void)setCancelBlock:(void (^)())cancelBlock
-{
- if (self.isCancelled)
- {
+- (void)setCancelBlock:(void (^)())cancelBlock {
+ if (self.isCancelled) {
if (cancelBlock) cancelBlock();
}
- else
- {
+ else {
_cancelBlock = [cancelBlock copy];
}
}
-- (void)cancel
-{
+- (void)cancel {
self.cancelled = YES;
- if (self.cacheOperation)
- {
+ if (self.cacheOperation) {
[self.cacheOperation cancel];
self.cacheOperation = nil;
}
- if (self.cancelBlock)
- {
+ if (self.cancelBlock) {
self.cancelBlock();
self.cancelBlock = nil;
}
View
6 SDWebImage/SDWebImagePrefetcher.h
@@ -23,15 +23,15 @@
* @param finishedCount The total number of images that were prefetched
* @param totalCount The total number of images that need to be prefetched
*/
-- (void)imagePrefetcher:(SDWebImagePrefetcher*)imagePrefetcher didPrefetchURL:(NSURL*)imageURL finishedCount:(NSUInteger)finishedCount totalCount:(NSUInteger)totalCount;
+- (void)imagePrefetcher:(SDWebImagePrefetcher *)imagePrefetcher didPrefetchURL:(NSURL