Skip to content

Instantly share code, notes, and snippets.

@ddribin
Created February 15, 2010 16:25
Show Gist options
  • Save ddribin/304766 to your computer and use it in GitHub Desktop.
Save ddribin/304766 to your computer and use it in GitHub Desktop.
@protocol DDAsyncTaskDelegate <NSObject>
- (void)setResult:(id)result;
- (void)setError:(NSError *)error;
@end
@protocol DDAsyncTask <NSObject>
- (void)startWithDelegate:(id<DDAsyncTaskDelegate>)delegate;
@end
id<DDFuture> DDStartAsyncTask(id<DDAsyncTask> asyncTask);
@interface UrlConnectionTask : NSObject <DDAsyncTask>
{
id<DDAsyncTaskDelegate> _delegate;
NSURLConnection * _connection;
NSMutableData * _responseData;
}
+ (id)urlConnectionTaskWithUrlRequest:(NSURLRequest *)request;
- (id)initWithUrlRequest:(NSURLRequest *)request;
- (void)startWithDelegate:(id<DDAsyncTaskDelegate>)delegate;
@end
@implementation UrlConnectionTask
+ (id)urlConnectionTaskWithUrlRequest:(NSURLRequest *)request;
{
id o = [[self alloc] initWithUrlRequest:request];
return [o autorelease];
}
- (id)initWithUrlRequest:(NSURLRequest *)request;
{
self = [super init];
if (self == nil)
return nil;
_connection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:NO];
return self;
}
- (void)dealloc
{
[_connection release];
[_responseData release];
[super dealloc];
}
- (void)startWithDelegate:(id<DDAsyncTaskDelegate>)delegate;
{
_delegate = [delegate retain];
[_connection scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[_connection start];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
[_delegate setError:error];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
[_delegate setResult:_responseData];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[_responseData release];
_responseData = [[NSMutableData alloc] init];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[_responseData appendData:data];
}
@end
{
NSURL * url = [NSURL URLWithString:@"http://www.example.com/"];
NSURLRequest * request = [NSURLRequest requestWithURL:url];
UrlConnectionTask * urlConnectionTask = [[UrlConnectionTask alloc] initWithUrlRequest:request];
id<DDFuture> futureData = DDStartAsyncTask(urlConnectionTask);
// This runs the run loop waiting for the result
NSError * error = nil;
NSData * response = [futureData result:&error];
if (response != nil) {
NSString * responseString = [[[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding] autorelease];
NSLog(@"String:\n%@", responseString);
} else {
NSLog(@"Error: %@ %@", error, [error userInfo]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment