HTML ソース コードの非同期フェッチには、AFNetworkingを使用することをお勧めします
1) 次に、AFHTTPCLient をサブクラス化します。次に例を示します。
//WebClientHelper.h
#import "AFHTTPClient.h"
@interface WebClientHelper : AFHTTPClient{
}
+(WebClientHelper *)sharedClient;
@end
//WebClientHelper.m
#import "WebClientHelper.h"
#import "AFHTTPRequestOperation.h"
NSString *const gWebBaseURL = @"http://dummyBaseURL.com/";
@implementation WebClientHelper
+(WebClientHelper *)sharedClient
{
static WebClientHelper * _sharedClient = nil;
static dispatch_once_t oncePredicate;
dispatch_once(&oncePredicate, ^{
_sharedClient = [[self alloc] initWithBaseURL:[NSURL URLWithString:gWebBaseURL]];
});
return _sharedClient;
}
- (id)initWithBaseURL:(NSURL *)url
{
self = [super initWithBaseURL:url];
if (!self) {
return nil;
}
[self registerHTTPOperationClass:[AFHTTPRequestOperation class]];
return self;
}
@end
2) 非同期で HTML ソース コードを要求し、このコードを関連する部分に配置します。
NSString *testNewsURL = @"http://whatever.com";
NSURL *url = [NSURL URLWithString:testNewsURL];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFHTTPRequestOperation *operationHttp =
[[WebClientHelper sharedClient] HTTPRequestOperationWithRequest:request success:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSString *szResponse = [[[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding] autorelease];
NSLog(@"Response: %@", szResponse );
}
failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
NSLog(@"Operation Error: %@", error.localizedDescription);
}];
[[WebClientHelper sharedClient] enqueueHTTPRequestOperation:operationHttp];