diff --git a/SDWebImage/SDWebImageDownloaderOperation.m b/SDWebImage/SDWebImageDownloaderOperation.m index 427d939e..65d568bd 100644 --- a/SDWebImage/SDWebImageDownloaderOperation.m +++ b/SDWebImage/SDWebImageDownloaderOperation.m @@ -88,6 +88,9 @@ typedef NSMutableDictionary SDCallbacksDictionary; _unownedSession = session; _callbacksLock = dispatch_semaphore_create(1); _coderQueue = dispatch_queue_create("com.hackemist.SDWebImageDownloaderOperationCoderQueue", DISPATCH_QUEUE_SERIAL); +#if SD_UIKIT + _backgroundTaskId = UIBackgroundTaskInvalid; +#endif } return self; } @@ -141,14 +144,7 @@ typedef NSMutableDictionary SDCallbacksDictionary; __weak __typeof__ (self) wself = self; UIApplication * app = [UIApplicationClass performSelector:@selector(sharedApplication)]; self.backgroundTaskId = [app beginBackgroundTaskWithExpirationHandler:^{ - __strong __typeof (wself) sself = wself; - - if (sself) { - [sself cancel]; - - [app endBackgroundTask:sself.backgroundTaskId]; - sself.backgroundTaskId = UIBackgroundTaskInvalid; - } + [wself cancel]; }]; } #endif @@ -212,18 +208,6 @@ typedef NSMutableDictionary SDCallbacksDictionary; [self done]; return; } - -#if SD_UIKIT - Class UIApplicationClass = NSClassFromString(@"UIApplication"); - if(!UIApplicationClass || ![UIApplicationClass respondsToSelector:@selector(sharedApplication)]) { - return; - } - if (self.backgroundTaskId != UIBackgroundTaskInvalid) { - UIApplication * app = [UIApplication performSelector:@selector(sharedApplication)]; - [app endBackgroundTask:self.backgroundTaskId]; - self.backgroundTaskId = UIBackgroundTaskInvalid; - } -#endif } - (void)cancel { @@ -262,11 +246,23 @@ typedef NSMutableDictionary SDCallbacksDictionary; SD_LOCK(self.callbacksLock); [self.callbackBlocks removeAllObjects]; SD_UNLOCK(self.callbacksLock); - self.dataTask = nil; - if (self.ownedSession) { - [self.ownedSession invalidateAndCancel]; - self.ownedSession = nil; + @synchronized (self) { + self.dataTask = nil; + + if (self.ownedSession) { + [self.ownedSession invalidateAndCancel]; + self.ownedSession = nil; + } + +#if SD_UIKIT + if (self.backgroundTaskId != UIBackgroundTaskInvalid) { + // If backgroundTaskId != UIBackgroundTaskInvalid, sharedApplication is always exist + UIApplication * app = [UIApplication performSelector:@selector(sharedApplication)]; + [app endBackgroundTask:self.backgroundTaskId]; + self.backgroundTaskId = UIBackgroundTaskInvalid; + } +#endif } }