Created
August 8, 2012 07:27
-
-
Save kishikawakatsumi/3293117 to your computer and use it in GitHub Desktop.
HTTPLoader
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// HTTPLoader.h | |
// | |
#import <Foundation/Foundation.h> | |
typedef void(^ HTTPLoaderCompletionBlock)(NSData *data, NSError *erorr); | |
@interface HTTPLoader : NSObject | |
+ (void)loadAsync:(NSURLRequest *)request complete:(HTTPLoaderCompletionBlock)block; | |
@end | |
// | |
// HTTPLoader.m | |
// | |
#import "HTTPLoader.h" | |
@interface HTTPFetcher : NSObject | |
@property (copy, nonatomic) HTTPLoaderCompletionBlock completionBlock; | |
@end | |
@implementation HTTPFetcher { | |
NSMutableData *receivedData; | |
NSInteger statusCode; | |
} | |
- (id)init { | |
self = [super init]; | |
if (self) { | |
receivedData = [NSMutableData data]; | |
} | |
return self; | |
} | |
- (void)requestGet:(NSURLRequest *)request { | |
NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self]; | |
[connection start]; | |
} | |
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { | |
if ([response isKindOfClass:[NSHTTPURLResponse class]]) { | |
NSHTTPURLResponse *res = (NSHTTPURLResponse *)response; | |
statusCode = res.statusCode; | |
if (statusCode >= 400) { | |
[connection cancel]; | |
NSError *error = [NSError errorWithDomain:NSURLErrorDomain code:statusCode userInfo:nil]; | |
[self connection:connection didFailWithError:error]; | |
} | |
} | |
} | |
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { | |
[receivedData appendData:data]; | |
} | |
- (void)connectionDidFinishLoading:(NSURLConnection *)connection { | |
if (self.completionBlock) { | |
self.completionBlock(receivedData, nil); | |
} | |
} | |
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { | |
if (self.completionBlock) { | |
self.completionBlock(nil, error); | |
} | |
} | |
@end | |
@implementation HTTPLoader | |
+ (void)loadAsync:(NSURLRequest *)request complete:(HTTPLoaderCompletionBlock)block { | |
HTTPFetcher *fetcher = [[HTTPFetcher alloc] init]; | |
fetcher.completionBlock = ^(NSData *data, NSError *error) { | |
if (block) { | |
block(data, error); | |
} | |
}; | |
[fetcher requestGet:request]; | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
[NSURLConnect sendSynchronizedRequest...]
を使えばいいじゃないですか。。