2013-02-23 6 views
0

웹 컨텐츠를 비동기 적으로로드하려고합니다. 내 viewdidappear 메서드에서 많은 양의 웹 호출이 있고 내 응용 프로그램이 매우 응답하지 않습니다. 콘텐츠의 동기 및 비동기 로딩 개념을 이해하고 있지만 비동기 적으로 완료되었는지 확인하는 방법을 알지 못합니다. 아래의 코드는 단순히 내 viewdidappear 메서드에 포함되어 있으며 동 기적으로로드되는 것으로 가정합니다. 비동기 적으로로드되도록하려면 어떻게 편집해야합니까? 다들 감사 해요!비동기 적으로 웹 컨텐츠로드

NSString *strURLtwo = [NSString stringWithFormat:@"http://website.com/json.php? 
id=%@&lat1=%@&lon1=%@",id, lat, lon]; 

NSData *dataURLtwo = [NSData dataWithContentsOfURL:[NSURL URLWithString:strURLtwo]]; 

NSArray *readJsonArray = [NSJSONSerialization JSONObjectWithData:dataURLtwo options:0 
error:nil]; 
NSDictionary *element1 = [readJsonArray objectAtIndex:0]; 

NSString *name = [element1 objectForKey:@"name"]; 
NSString *address = [element1 objectForKey:@"address"]; 
NSString *phone = [element1 objectForKey:@"phone"]; 

답변

2
당신은 NSURLConnectionDelegate을 사용할 수 있습니다

:

// Your public fetch method 
-(void)fetchData 
{ 
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://website.com/json.php?id=%@&lat1=%@&lon1=%@",id, lat, lon]]; 

    // Put that URL into an NSURLRequest 
    NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url]; 

    // Create a connection that will exchange this request for data from the URL 
    connection = [[NSURLConnection alloc] initWithRequest:req 
               delegate:self 
             startImmediately:YES]; 
} 

구현 위임 방법 :

- (void)connection:(NSURLConnection *)conn didReceiveData:(NSData *)data 
{ 
    // Add the incoming chunk of data to the container we are keeping 
    // The data always comes in the correct order 
    [jsonData appendData:data]; 
} 


- (void)connectionDidFinishLoading:(NSURLConnection *)conn 
{ 
    // All data is downloaded. Do your stuff with the data 
    NSArray *readJsonArray = [NSJSONSerialization jsonData options:0 error:nil]; 
    NSDictionary *element1 = [readJsonArray objectAtIndex:0]; 

    NSString *name = [element1 objectForKey:@"name"]; 
    NSString *address = [element1 objectForKey:@"address"]; 
    NSString *phone = [element1 objectForKey:@"phone"]; 

    jsonData = nil; 
    connection = nil; 
} 

// Show AlertView if error 
- (void)connection:(NSURLConnection *)conn didFailWithError:(NSError *)error 
{ 
    connection = nil; 
    jsonData = nil; 
    NSString *errorString = [NSString stringWithFormat:@"Fetch failed: %@", [error  localizedDescription]]; 

    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Error" message:errorString delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil]; 
    [alertView show]; 
} 
+0

감사합니다. 내 viewdidload/viewdidappear 메서드에서 이름, 주소 및 전화 NSString을 참조 할 수 있습니까? 비동기 적으로로드하는 경우 어떻게 데이터를 전달합니까? – Brandon

+0

viewController를 NSURLConnectionDelegate로 만들려면 viewDidLoad에서 fetchData 메서드를 실행 한 다음 connectionDidFinishLoading에서 가져올 때 가져온 데이터 (이름, 주소 및 전화)를 사용합니다. 다른 클래스를 위임자로 만들면 NSNotificationCenter를 사용하여 완료되었을 때 데이터를 게시 할 수 있습니다 (뷰 컨트롤러에 알림을위한 관찰자를 추가). – SuperGlenn

1

비동기 웹 콘텐츠로드의 경우 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]; 
관련 문제