Skip to content

Instantly share code, notes, and snippets.

@corosukeK
Created August 8, 2012 16:44
Show Gist options
  • Save corosukeK/3296536 to your computer and use it in GitHub Desktop.
Save corosukeK/3296536 to your computer and use it in GitHub Desktop.
HTTPLoader(改良してみるなど)
//
// HTTPLoader.m
// HTTPLoader
//
// Created by Keisuke Kimura on 2012/08/08.
// Copyright (c) 2012年 Keisuke Kimura. All rights reserved.
//
#import "HTTPLoader.h"
static NSOperationQueue* operationQueue;
static dispatch_queue_t serialQueue;
@implementation HTTPLoader
+ (NSOperationQueue*)operationQueue
{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
operationQueue = [[NSOperationQueue alloc] init];
[operationQueue setMaxConcurrentOperationCount:5];
});
return operationQueue;
}
+ (dispatch_queue_t)serialDispatchQueue
{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
serialQueue = dispatch_queue_create("com.corosuke.httploader.serial",NULL);
});
return serialQueue;
}
+ (void)loadAsync:(NSURLRequest*)request
owner:(id)owner
complete:(CompleteWithWeakSelfBlock)completeBlock
{
__block id inBlockSelf = owner;
dispatch_sync([HTTPLoader serialDispatchQueue], ^{
__block NSBlockOperation* operation = [[NSBlockOperation alloc] init];
[operation addExecutionBlock:^{
NSData* responseData = nil;
NSURLResponse* response = nil;
NSError* error = nil;
responseData = [NSURLConnection sendSynchronousRequest:request
returningResponse:&response
error:&error];
if(!operation.isCancelled){
dispatch_sync(dispatch_get_main_queue(), ^{
completeBlock(responseData, error, inBlockSelf);
});
}
}];
[[HTTPLoader operationQueue] addOperation:operation];
});
}
+ (void)cancelAll
{
dispatch_sync([HTTPLoader serialDispatchQueue], ^{
[[HTTPLoader operationQueue] cancelAllOperations];
});
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment