Tags

, , , , , ,

As part of research for my ToDoGenius project I was playing with HTTP requesting from iOS.

I created sample project which can be used as starting point, HttpClientTest

HttpClientTest support synchronized data retrieve ( this approach is not a good choose because it blocks main thread ) and asynchronized retrieve. Retrieved data is shown in UITextView, pretty simple. For server I’m using nodeJS static file server.

If you want to “try out” blocking of main thread during sync vs async request download use server_withtimeout.js

For synchronized request retrieve code looks like:

[status setText:@"Retrieving response sync"];
[response setText:@""];

NSURL* requestUrl = [[NSURL alloc] initWithString:url.text];
NSURLRequest* request = [NSURLRequest requestWithURL:requestUrl cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:60.0];

NSData* data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];

NSString* responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

[response setText:responseString];

[status setText:@"Response retrieved sync"];

For asynchronized retrieve ViewController is used as NSUrlConnection delegate

- (void)connection:(NSURLConnection*) connection didReceiveResponse:(NSURLResponse *)response
{
    NSLog(@"Response recieved");
}

- (void)connection:(NSURLConnection*) connection didReceiveData:(NSData *)data
{
    NSLog(@"Data recieved");    

    NSString* responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

    [response setText:responseString];

    [status setText:@"Response retrieved async"];
}

Code which starts synchronized request is:

[status setText:@"Retrieving response async"];
[response setText:@""];

NSURL* requestUrl = [[NSURL alloc] initWithString:url.text];
NSURLRequest* request = [NSURLRequest requestWithURL:requestUrl cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:60.0];

NSURLConnection* connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection start];
Advertisements