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;
}
'iPhone Dev.' 카테고리의 다른 글
Debug 모드에서만 NSLog 로깅하기 (0) | 2013.04.22 |
---|---|
Default.png 설정 (0) | 2013.04.22 |
IB없는 Window-based Application 프로젝트 시작하기 (0) | 2011.05.11 |
NSArray를 plist 파일로 저장 (0) | 2011.05.04 |
C# Push Notification Provider 구현 (8) | 2010.07.31 |