Hi Rick,
Don't use the NSURLConnection synchronous method, it's non-cancellable and
blocks the calling thread until timeout, or completion.
A better block based NSURLRequest method would be as follows (typed in Mail
from memory):
> @implementation NSOperationQueue (MyAdditions)
>
> typedef NSData * (^MyResponseProviderBlock)(NSURLResponse **, NSError **); //
> Note: this mimics the +sendSynchronousRequest:… signature
>
> - (NSOperation *)addOperationWithRequest:(NSURLRequest *)request
> completionBlock:(void (^)(MyResponseProviderBlock))completionBlock {
> _MyURLConnectionOperation *requestOperation =
> [[[_MyURLConnectionOperation alloc] initWithRequest:request] autorelease];
> [self addOperation:requestOperation];
> if (completionBlock == nil) {
> return requestOperation;
> }
>
> NSBlockOperation *callbackOperation = [NSBlockOperation
> blockOperationWithBlock:^ {
> MyResponseProviderBlock responseProvider = ^ NSData *
> (NSURLResponse **responseRef, NSError **errorRef) {
> NSData *bodyData = [requestOperation bodyData];
> if (bodyData == nil) {
> if (errorRef != NULL) {
> *errorRef = [requestOperation error];
> }
> return nil;
> }
>
> if (responseRef != NULL) {
> *responseRef = [requestOperation response];
> }
> return bodyData;
> };
> completionBlock(responseProvider);
> }];
> [callbackOperation addDependency:requestOperation];
> [self addOperation:callbackOperation];
>
> return callbackOperation;
> }
>
> @end
The implementation of _MyURLConnectionOperation is left as an exercise to the
reader.
• It is an -isConcurrent NSOperation subclass, check the docs if you're
uncertain of the implications.
• It creates an NSURLConnection and schedules it on the main run loop,
collecting the results.
This provides a way to perform an NSURLRequest asynchronously, with
cancellation, without having to create an NSURLConnection and it's callbacks.
It essentially 'fakes' the synchronous API whilst still performing the request
asynchronously.
NB: if you are expecting large response entities, you will want to add a
variation that streams the received data to disk.
Keith
_______________________________________________
Cocoa-dev mailing list ([email protected])
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com
This email sent to [email protected]