次のように CustomNSURLConnection クラスを作成します。
CustomNSURLConnection.h
#import <Foundation/Foundation.h>
typedef void (^ServiceBlock)(NSString *result);
@interface CustomNSURLConnection : NSURLConnection
@property (nonatomic, copy) ServiceBlock serviceBlock;
@property (nonatomic, retain) NSMutableData *serviceResponseData;
- (id)initWithRequest:(NSURLRequest *)request delegate:(id)delegate usingCallback:(ServiceBlock)callBackBlock;
@end
CustomNSURLConnection.m
#import "CustomNSURLConnection.h"
@implementation CustomNSURLConnection
@synthesize serviceBlock, serviceResponseData;
-(id)initWithRequest:(NSURLRequest *)request delegate:(id)delegate usingCallback:(ServiceBlock)callBackBlock{
self = [super initWithRequest:request delegate:delegate];
if (self) {
self.serviceBlock = callBackBlock;
self.serviceResponseData = [NSMutableData data];
}
return self;
}
@end
WebServiceHitter.h
#import "CoffeeshopCustomNSURLConnection.h"
@interface WebServiceHitter : NSObject
@end
WebServiceHitter.m
@interface CoffeeShopWebServiceHitter()
@property (nonatomic, retain) NSMutableData *responseData;
#pragma mark - NSURLConnection Delegate Methods
- (void)connection:(CustomNSURLConnection *)connectionDb didReceiveResponse:(NSURLResponse *)response {
CustomNSURLConnection *specializedNSURLDataConnection = (CustomNSURLConnection *)connectionDb;
[specializedNSURLDataConnection.serviceResponseData setLength:0];
}
- (void)connection:(CustomNSURLConnection *)connectionDb didReceiveData:(NSData *)data {
CustomNSURLConnection *specializedNSURLDataConnection = (CoffeeshopCustomNSURLConnection *)connectionDb;
[specializedNSURLDataConnection.serviceResponseData appendData:data];
}
- (void)connection:(CustomNSURLConnection *)connectionDb didFailWithError:(NSError *)error {
NSLog(@"Connection failed: %@", [error description]);
}
- (void)connectionDidFinishLoading:(CustomNSURLConnection *)finishedWithConnection {
CustomNSURLConnection *specializedNSURLConnection = (CustomNSURLConnection*)finishedWithConnection;
NSString *responseString = [[NSString alloc] initWithData:specializedNSURLConnection.serviceResponseData encoding:NSASCIIStringEncoding];
specializedNSURLConnection.serviceResponseData = nil;
specializedNSURLConnection.serviceBlock(responseString);
}
@end
使用状況に応じて、webservicehitter ファイルで Web サービス リクエストを作成します。