Skip to content

Instantly share code, notes, and snippets.

@kishikawakatsumi
Created August 8, 2012 07:27
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kishikawakatsumi/3293117 to your computer and use it in GitHub Desktop.
Save kishikawakatsumi/3293117 to your computer and use it in GitHub Desktop.
HTTPLoader
//
// 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
@TonnyXu
Copy link

TonnyXu commented Aug 24, 2012

[NSURLConnect sendSynchronizedRequest...]を使えばいいじゃないですか。。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment