Add option to continue download in background

This commit is contained in:
Luis Solano Bonet 2013-10-22 16:32:36 -04:00 committed by Olivier Poitrey
parent 5df0eafc92
commit c79e6ffe04
2 changed files with 32 additions and 1 deletions

View File

@ -23,7 +23,10 @@ typedef enum
* 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,
SDWebImageDownloaderContinueInBackground = 1 << 4
} SDWebImageDownloaderOptions;
typedef enum

View File

@ -23,6 +23,10 @@
@property (strong, nonatomic) NSMutableData *imageData;
@property (strong, nonatomic) NSURLConnection *connection;
#if TARGET_OS_IPHONE && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_4_0
@property (assign, nonatomic) UIBackgroundTaskIdentifier backgroundTaskId;
#endif
@end
@implementation SDWebImageDownloaderOperation
@ -57,6 +61,25 @@
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 (sself)
{
[sself cancel];
[[UIApplication sharedApplication] endBackgroundTask:sself.backgroundTaskId];
sself.backgroundTaskId = UIBackgroundTaskInvalid;
}
}];
}
#endif
self.executing = YES;
self.connection = [NSURLConnection.alloc initWithRequest:self.request delegate:self startImmediately:NO];
@ -343,5 +366,10 @@
}
}
- (BOOL)shouldContinueWhenAppEntersBackground
{
return self.options & SDWebImageDownloaderContinueInBackground;
}
@end