Skip to content

Instantly share code, notes, and snippets.

@cooldaemon
Created July 11, 2009 14:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cooldaemon/145264 to your computer and use it in GitHub Desktop.
Save cooldaemon/145264 to your computer and use it in GitHub Desktop.
Asynchronous test in Objective-C.
#import "TestHttp.h"
int main(int argc, char *argv[]) {
TestHttp *th = [[TestHttp alloc] init];
[th runTest];
return 0;
}
CC = gcc
SOURCES = $(wildcard *.m)
OBJECTS = $(SOURCES:%.m=%.o)
TARGET = test
$(TARGET): $(OBJECTS)
$(CC) $(OBJECTS) -o $@ -framework Foundation
.m.o:
$(CC) -c $<
clean:
rm -f $(TARGET) $(OBJECTS)
#import <Foundation/Foundation.h>
@interface TestHttp : NSObject {
BOOL is_loaded;
NSURLConnection *conn;
NSHTTPURLResponse *response;
NSMutableData *data;
}
- (void)runTest;
@end
#import "TestHttp.h"
@implementation TestHttp
- (id)init {
self = [super init];
if (self == nil) {
return nil;
}
is_loaded = NO;
data = [[NSMutableData alloc] init];
return self;
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)get_response {
response = [get_response retain];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)get_data {
[data appendData:get_data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog([error localizedDescription]);
is_loaded = YES;
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
is_loaded = YES;
}
- (void)sendHttpRequest {
NSURLRequest *req = [NSURLRequest
requestWithURL:[NSURL
URLWithString:@"http://www.google.com/"
]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0
];
conn = [[NSURLConnection alloc] initWithRequest:req delegate:self];
}
- (void)waitHttpResponse {
BOOL is_running;
do {
is_running = [[NSRunLoop currentRunLoop]
runMode:NSDefaultRunLoopMode
beforeDate:[NSDate dateWithTimeIntervalSinceNow:1.0]
];
} while (is_running && !is_loaded);
}
- (void)runTest {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc]init];
[self sendHttpRequest];
[self waitHttpResponse];
@try {
int status = [response statusCode];
NSAssert1(status == 200, @"status is %d.", status);
unsigned char bytes[[data length]];
[data getBytes:bytes];
NSLog(@"Received Data: %s\n", (char *)bytes);
}
@catch (NSException *ex) {
NSLog(@"Name : %@\n", [ex name]);
NSLog(@"Reason: %@\n", [ex reason]);
}
[pool release];
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment