Created
September 12, 2009 14:44
-
-
Save tjweir/185858 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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