So having worked on two apps now that required many requests to web servers to be made in the background, I decided to write a simple to use wrapper around the more complex parts which exposes what I hope is a clear api.

The basic concept is an extension to NSOperation overriding the methods:

- (void)start;
- (BOOL)isConcurrent;
- (BOOL)isFinished;
- (BOOL)isExecuting;

I aslo made some simple Http Request and response wrappers and a protocol for receiving the responses called HttpResponseDelegate

@protocol HttpResponseDelegate

- (void)requestResponseRecieved:(HttpResponse *)res;

- (void)requestResponseError:(HttpResponse *)res;
- (void)requestFailed:(NSError *)err;
- (void)request:(HttpRequest *)req AndOpCancelled:(HttpOperation *)op;

The wrapper will let you send both post and Get requests which are cancelable and will be performed on background threads; although it doesn’t yet allow for the posting of multipart data such as images, but I plan to add that in time. I know there are other libraries out there for this kind of thing, but I wanted to do it for myself as a personal experiment and project. I have put the code up on git hub. Feel free to use it as you wish Git Hub Repo

Basic Usage

Just to give a quick usage example:

in a viewController implementing the HttpResponseDelegate protocol you would do something along the lines of :

- (void)someMethod{
//this is a singleton class that manages adding ops to a single operation que
HttpSync * httpFactory = [HttpSync getSharedInstance];
HttpRequest * req = [[HttpRequest alloc]initWithUrl:@""];
HttpRequest * req2 = [[HttpRequest alloc]initWithUrl:@""];

//send some params
[req2 setParamWithKey:@"someparam" AndValue:@"somevalue"];

//change to POST req.method = HTTP_METHOD_POST;
//default method is GET

req.method = HTTP_METHOD_GET;
//make the operations possibly could add this functionality to the HttpSync class in future
HttpOperation * httpOp = [[HttpOperation alloc] initWithRequest:req AndResponseDelegate:self];
HttpOperation * httpOp2 = [[HttpOperation alloc] initWithRequest:req2 AndResponseDelegate:self];
[httpFactory sendOperation:httpOp];
[httpFactory sendOperation:httpOp2];
[req2 release];
[req release];
[httpOp release];
[httpOp2 release];


#pragma mark HttpResponseDelegate methods

- (void)requestResponseRecieved:(HttpResponse *)res{
if(res.responseCode == HTTP_RESPONSE_CODE_OK){
//do your thing get the content by using
NSData * resData = res.rawResponse;
NSString * resString = res.responseAsUTF8DecodedString;
//see the headers
NSDictionary * headers = res.responseHeaders;

//check the response code and respond accordingly

Gah objective c does not come out well on the blog. Hopefully you can follow it. Will be adding some improvements as I hope to use this library in some of my future projects.

Sorry, the comment form is closed at this time.

© 2012 Craig Brookes Suffusion theme by Sayontan Sinha