NSURLConnection 사용하기

2013. 4. 25. 00:09 from iPhone Dev.

NSURLConnection, NSURLConnectionDelegate 사용 예제

다음 코드는 야후 Weather API를 사용하여 데이터를 받아오는 것을 구현


Delegate 메소드

1)데이터 수신

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data


2)연결 오류

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error


3)연결 종료

- (void)connectionDidFinishLoading:(NSURLConnection *)connection


#pragma mark -

#pragma mark Custom Methods


- (void)loadData {

    NSLog(@"loadData");


    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];


    NSURL *weatherURL = [[NSURL alloc] initWithString:@"http://weather.yahooapis.com/forecastrss?w=2502265"];

    NSURLConnection *URLConnection = [[NSURLConnection alloc] initWithRequest:[NSURLRequest requestWithURL:weatherURL] delegate:self];

    [URLConnection release];

    [weatherURL release];

}


#pragma mark -

#pragma mark NSURLConnectionDelegate


- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {

    NSLog(@"connection:didReceiveData:");


    if (receiveData == nil) {

        receiveData = [[NSMutableData alloc] init];

    }

    [receiveData appendData:data];

}


- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {

    NSLog(@"connection:didFailWithError:");


    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];


    [receiveData release];

    receiveData = nil;

}


- (void)connectionDidFinishLoading:(NSURLConnection *)connection {

    NSLog(@"connectionDidFinishLoading:");


    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];


    NSString *receiveString = [[[NSString alloc] initWithData:receiveData encoding:CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingEUC_KR)] autorelease];


    NSLog(@"%@", receiveString);


    [receiveData release];

    receiveData = nil;

}


Posted by NuBiFoRM :