2010/08/24

An NSOperation that runs an HTTP request. NSURLConnection backed.

 IZHTTPOperation is a general purpose NSOperation that runs HTTP requests.
 You initialise it with an HTTP request and then, when you run the operation,
 it sends the request and gathers the response.  It is quite a complex
 object because it handles a wide variety of edge cases, but it's very
 easy to use in simple cases:

 1. create the operation with the URL you want to get

 op = [[[IZHTTPOperation alloc] initWithURL:url] autorelease];

 2. set up any non-default parameters, for example, set which HTTP
 content types are acceptable

 op.acceptableContentTypes = [NSSet setWithObject:@"text/html"];

 3. enqueue the operation

 [queue addOperation:op];

 4. finally, when the operation is done, use the lastResponse and
 error properties to find out how things went

 [op setCompletionBlock:^
 {
    [[NSOperationQueue mainQueue] addOperationWithBlock:^
    {
        // Do nothing if operation was cancelled.
        if ([op isCancelled])
            return;

        NSError *error = op.error;
        if (error)
        {
            // Handle the error here...
            return;
        }
      
        NSData *responseBody = op.responseBody;
        // Process the body here...
    }];
 }];

 As mentioned above, IZHTTPOperation is very general purpose.  There are a
 large number of configuration and result options available to you.

 o You can specify a NSURLRequest rather than just a URL.

 o You can configure the run loop on which the NSURLConnection is scheduled.

 o You will receive NSNotifications on the main thread when a network activity has started/stopped.

 o You can use the autoretry functionality to retry when the host becomes reachable. (Depends on Reachability)

 o You can specify what HTTP status codes and content types are OK.

 o You can set an authentication delegate to handle authentication challenges.

 o You can accumulate responses in memory or in a NSOutputStream.

 o For in-memory responses, you can specify a default response size
 (used to size the response buffer) and a maximum response size
 (to prevent unbounded memory use).

 o You can get at the last request and the last response, to track
 redirects.

 o There are a variety of funky debugging options to simulator errors
 and delays.

 Finally, it's perfectly reasonable to subclass IZHTTPOperation to meet your
 own specific needs.

Enhanced by Zemanta

0 comments:

Post a Comment