비동기 웹 콘텐츠로드의 경우 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://whateverBaseURL.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) 요구를 비동기 웹 콘텐츠를 모든 관련 부분에이 코드를 넣어
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);
//PUT your code here
}
failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
NSLog(@"Operation Error: %@", error.localizedDescription);
}];
[[WebClientHelper sharedClient] enqueueHTTPRequestOperation:operationHttp];
감사합니다. 내 viewdidload/viewdidappear 메서드에서 이름, 주소 및 전화 NSString을 참조 할 수 있습니까? 비동기 적으로로드하는 경우 어떻게 데이터를 전달합니까? – Brandon
viewController를 NSURLConnectionDelegate로 만들려면 viewDidLoad에서 fetchData 메서드를 실행 한 다음 connectionDidFinishLoading에서 가져올 때 가져온 데이터 (이름, 주소 및 전화)를 사용합니다. 다른 클래스를 위임자로 만들면 NSNotificationCenter를 사용하여 완료되었을 때 데이터를 게시 할 수 있습니다 (뷰 컨트롤러에 알림을위한 관찰자를 추가). – SuperGlenn