Skip to content

Instantly share code, notes, and snippets.

@tjweir
Created September 12, 2009 14:44
Show Gist options
  • Save tjweir/185858 to your computer and use it in GitHub Desktop.
Save tjweir/185858 to your computer and use it in GitHub Desktop.
//http://www.mikeash.com/?page=pyblog/friday-qa-2009-08-14-practical-blocks.html
// NSURLConnection
@implementation NSURLConnection (BlocksAdditions)
+ (void)sendAsynchronousRequest: (NSURLRequest *)request
completionBlock: (void (^)(NSData *data, NSURLResponse *response, NSError *error))block
{
NSThread *originalThread = [NSThread currentThread];
RunInBackground(^{
WithAutoreleasePool(^{
NSURLResponse *response = nil;
NSError *error = nil;
NSData *data = [self sendSynchronousRequest: request returningResponse: &response error: &error;];
RunOnThread(originalThread, NO, ^{ block(data, response, error); });
});
});
}
@end
// Example:
NSURLRequest *request = [NSURLRequest requestWithURL: [NSURL URLWithString: @"http://www.google.com/"]];
[NSURLConnection sendAsynchronousRequest: request
completionBlock: ^(NSData *data, NSURLResponse *response, NSError *error){
NSLog(@"data: %ld bytes response: %@ error: %@", (long)[data length], response, error);
}];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment