#import <UIKit/UIKit.h>
//HttpEx의선언
@interface HttpEx : UIViewController <UITextFieldDelegate> {
UITextField* _textField;
UIActivityIndicatorView* _indicator;
NSMutableData* _data;
}
@end
#import "HttpEx.h"
#define URL_TEST @"http://npaka.net/iphone/test.txt"
#define BTN_READ 0
//HttpEx의구현
@implementation HttpEx
//텍스트필드 생성
- (UITextField*)makeTextField:(CGRect)rect text:(NSString*)text {
UITextField* textField=[[[UITextField alloc] init] autorelease];
[textField setText:text];
[textField setFrame:rect];
[textField setReturnKeyType:UIReturnKeyDone];
[textField setBackgroundColor:[UIColor whiteColor]];
[textField setBorderStyle:UITextBorderStyleRoundedRect];
[_textField setDelegate:self];
return textField;
}
//텍스트버튼 생성
- (UIButton*)makeButton:(CGRect)rect text:(NSString*)text tag:(int)tag {
UIButton* button=[UIButton buttonWithType:UIButtonTypeRoundedRect];
[button setFrame:rect];
[button setTitle:text forState:UIControlStateNormal];
[button setTag:tag];
[button addTarget:self action:@selector(clickButton:)
forControlEvents:UIControlEventTouchUpInside];
return button;
}
//데이터→스트링
- (NSString*)data2str:(NSData*)data {
return [[[NSString alloc] initWithData:data
encoding:NSUTF8StringEncoding] autorelease];
}
//GET방식으로HTTP통신
- (void)http2data:(NSString*)url delegate:(id)delegate {
NSURLRequest* request=[NSURLRequest
requestWithURL:[NSURL URLWithString:url]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:30.0];
[NSURLConnection connectionWithRequest:request
delegate:delegate];
//인디케이터 에니메이션의 개시
[_indicator startAnimating];
}
//데이터수신시작할때 호출NSURLConnection의 델리게이트
- (void)connection:(NSURLConnection*)connection
didReceiveResponse:(NSURLResponse*)response {
if (_data!=nil) [_data release];
_data=[[NSMutableData data] retain];
}
//데이터수신시 호출NSURLConnection의 델리게이트
- (void)connection:(NSURLConnection*)connection
didReceiveData:(NSData*)data {
[_data appendData:data];
}
//데이터수신완료시 호출NSURLConnection의 델리게이트
- (void)connectionDidFinishLoading:(NSURLConnection*)connection {
_textField.text=[self data2str:_data];
[_data release];
_data=nil;
//인디케이터 에니메이션의 정지
[_indicator stopAnimating];
}
//데이터수신실패시 호출NSURLConnection의 델리게이트
- (void)connection:(NSURLConnection*)connection
didFailWithError:(NSError*)error {
_textField.text=@"통신에러";
//인디케이터 에니메이션의 정지
[_indicator stopAnimating];
}
//초기화
- (void)viewDidLoad {
[super viewDidLoad];
//텍스트필드의 생성
_textField=[[self makeTextField:CGRectMake(0,0,300,32)
text:@""] retain];
[self.view addSubview:_textField];
//접속 버튼 생성
UIButton* btnRead=[self makeButton:CGRectMake(0,50,90,40)
text:@"접속" tag:BTN_READ];
[self.view addSubview:btnRead];
//인디케이터의 생성
_indicator=[[UIActivityIndicatorView alloc] init];
[_indicator setFrame:CGRectMake(140,140,40,40)];
[_indicator setActivityIndicatorViewStyle:
UIActivityIndicatorViewStyleWhiteLarge];
[_indicator setHidesWhenStopped:YES];
[self.view addSubview:_indicator];
//변수의 초기화
_data=nil;
}
- (void)dealloc {
[_textField release];
[_indicator release];
[_data release];
[super dealloc];
}
//텍스트필드에서 리턴키 눌렸을때 호출
- (BOOL)textFieldShouldReturn:(UITextField*)sender {
[sender resignFirstResponder];
return YES;
}
//버튼클릭시 호출
- (IBAction)clickButton:(UIButton*)sender {
if (sender.tag==BTN_READ) {
[self http2data:URL_TEST delegate:self];
}
}
- (BOOL)shouldAutorotateToInterfaceOrientation:
(UIInterfaceOrientation)orientation {
return YES;
}
@end
NSData 구현예
// NSDictionary으로 NSData를생성
NSDictionary *dic =[NSDictionary dictionaryWithObject:@"값" forKey:@"키"];
NSData *d = [NSKeyedArchiver archivedDataWithRootObject:dic];
//파일으로 NSData를 생성
NSBundle *bundle = [NSBundle mainBundle];
NSString *path = [bundle pathForResource:@"파일명" ofType:@"확장자"];
NSData *d = [[NSData alloc] initWithContentsOfFile:path];
// NSDictionary형→NSData형→NSDictionary형
// NSDictionary오브젝트 생성
NSDictionary *dic =[NSDictionary dictionaryWithObject:@"hoge" forKey:@"KEY"];
//생성한 오브젝트를 NSData형으로 변환
NSData *d = [NSKeyedArchiver archivedDataWithRootObject:dic];
// NSData형의 오브젝트를NSDictionary형으로 변환
NSDictionary *reverse = [NSKeyedUnarchiver unarchiveObjectWithData:d];
UIActivityIndicatorView 구현예
로딩등의 이유로 처리지연시 유저에게 처리중임을 표시해야할경우 사용
// 일반생성예
UIActivityIndicatorView *ai = [[UIActivityIndicatorView alloc] init];
// 사이즈를 지정해서 생성
UIActivityIndicatorView *ai =
[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
// 스타일을 지정해서 생성
UIActivityIndicatorView *ai =
[[UIActivityIndicatorView alloc]
initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
【UIActivityIndicatorView의 주요 프로퍼티】
프로퍼티명/반환형 |
설명 |
hidesWhenStopped |
에니메이션이정지되었을때 표시를 설정 |
activityIndicatorViewStyle |
스타일을 설정 |
【UIActivityIndicatorView의주요메소드】
메소드 |
설명 |
-(void)startAnimating |
에니메이션을 개시함 |
-(void)stopAnimating |
에니메이션을 정지함 |
-(BOOL)isAnimating |
에니메이션중인지 아닌지를 반환 |
// 인디케이터 예문
UIActivityIndicatorView *ai = [[UIActivityIndicatorView alloc] init];
ai.frame = CGRectMake(0, 0, 50, 50);
ai.center = self.view.center;
ai.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhiteLarge;
[self.view addSubview:ai];
[ai startAnimating]; // 에니메이션을 개시하고 싶을때 호출
[ai stopAnimating]; // 에니메이션을 중지하고 싶을때 호출
NSURLRequest와NSMutableURLRequest의 차이점
- NSMutableURLRequest가 생성한 인스턴스의 할용도가 높다
- NSMutableURLRequest는 post방식으로 전송가능
- NSMutableURLRequest는 http헤더를 설정가능
'아이폰개발' 카테고리의 다른 글
[아이폰개발] 참고 사이트 (0) | 2011.02.16 |
---|---|
[아이폰개발] 메세징 원리 라이브러리 미번역 (0) | 2011.02.10 |
[아이폰개발] 탭바 인터페이스 라이브러리 번역 (0) | 2011.02.10 |
[아이폰개발] hpple 사용예 (0) | 2011.01.28 |
[아이폰개발] 오브젝트별 참고사이트 (0) | 2011.01.21 |