Authored by Charlie Savage
Committed by Olivier Poitrey

This is an attempt to avoid the crashes in #341.

It won't fix the underlying issue but I hope it will avoid it in most cases.
The various crash reports indicate the underlying download operation is being
freed before the async block in dataReceived is being executed.

This fix change tries to avoid every calling the async block.
@@ -160,10 +160,7 @@ @@ -160,10 +160,7 @@
160 self.progressBlock(0, expected); 160 self.progressBlock(0, expected);
161 } 161 }
162 162
163 - dispatch_async(self.queue, ^  
164 - {  
165 - self.imageData = [NSMutableData.alloc initWithCapacity:expected];  
166 - }); 163 + self.imageData = [NSMutableData.alloc initWithCapacity:expected];
167 } 164 }
168 else 165 else
169 { 166 {
@@ -182,11 +179,11 @@ @@ -182,11 +179,11 @@
182 179
183 - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data 180 - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
184 { 181 {
185 - dispatch_async(self.queue, ^  
186 - {  
187 - [self.imageData appendData:data]; 182 + [self.imageData appendData:data];
188 183
189 - if ((self.options & SDWebImageDownloaderProgressiveDownload) && self.expectedSize > 0 && self.completedBlock) 184 + if ((self.options & SDWebImageDownloaderProgressiveDownload) && self.expectedSize > 0 && self.completedBlock)
  185 + {
  186 + dispatch_async(self.queue, ^
190 { 187 {
191 // The following code is from http://www.cocoaintheshell.com/2011/05/progressive-images-download-imageio/ 188 // The following code is from http://www.cocoaintheshell.com/2011/05/progressive-images-download-imageio/
192 // Thanks to the author @Nyx0uf 189 // Thanks to the author @Nyx0uf
@@ -254,7 +251,8 @@ @@ -254,7 +251,8 @@
254 } 251 }
255 252
256 CFRelease(imageSource); 253 CFRelease(imageSource);
257 - } 254 + });
  255 +
258 NSUInteger received = self.imageData.length; 256 NSUInteger received = self.imageData.length;
259 dispatch_async(dispatch_get_main_queue(), ^ 257 dispatch_async(dispatch_get_main_queue(), ^
260 { 258 {
@@ -263,7 +261,7 @@ @@ -263,7 +261,7 @@
263 self.progressBlock(received, self.expectedSize); 261 self.progressBlock(received, self.expectedSize);
264 } 262 }
265 }); 263 });
266 - }); 264 + }
267 } 265 }
268 266
269 - (void)connectionDidFinishLoading:(NSURLConnection *)aConnection 267 - (void)connectionDidFinishLoading:(NSURLConnection *)aConnection