The following code is an attempt to me better understand [NSURLConnection sendAsynchronousRequest:queue:completionHandler]
.
There are NSLog
statements in the completionHandler
block, but when I run this in main.m
in XCode from a command line project, it never enters the completionHandler
blocks. I've tried using the different queues, mainQueue
and currentQueue
but neither work.
My hunch is that the queue is being deallocated before the request is completed and that retain cycles are involved.
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[]) {
@autoreleasepool {
NSCache *myCache = [[NSCache alloc] init];
NSArray *images = @[
@"https://i.stack.imgur.com/E66qr.png",
@"http://www.tiempoyquimera.com/wp-content/uploads/2010/01/Euro-Trash-Girl-2010.jpg",
@"http://1.bp.blogspot.com/-Mxd8AB2nbQY/UYCISJiQz3I/AAAAAAAAAH8/Tc43U8aa9dM/s1600/Tarantino10colhans_1460858i.jpg",
@"https://awestruckwanderer.files.wordpress.com/2014/02/alan-watts.png",
@"http://www.esalen.org/sites/default/files/photo_images/20120201_DELLIS__MG_9612_711.jpg"];
for (NSString *image in images){
NSURL *myURL = [NSURL URLWithString:image];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:myURL];
NSLog(@"Can handle request %@", @([NSURLConnection canHandleRequest:request]));
NSOperationQueue *queue = [[NSOperationQueue alloc]init];
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
NSLog(@"In the completion handler");
if (!error)
{
// save data to cache with url as key
NSLog(@"Image Added to Cache");
[myCache setObject:data
forKey:myURL];
} else
{
NSLog(@"Image Not Added to Cache");
}
}];
}
}
return 0;
}