'2011/02/25'에 해당되는 글 1건

  1. 2011.02.25 [아이폰개발] IB없이 HTTP통신 예제

#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
BOOL

에니메이션이정지되었을때 표시를 설정
 YES:인디케이터를 비표시함(디폴트)
 NO:인디케이터를 표시함

activityIndicatorViewStyle
UIActivityIndicatorViewStyle

스타일을 설정
 UIActivityIndicatorViewStyleWhite:표준사이즈(흰색)
 UIActivityIndicatorViewStyleGray:표준사이즈(회색)
 UIActivityIndicatorViewStyleWhiteLarge:큰사이즈(흰색)


 

 

 

UIActivityIndicatorView의주요메소드】


메소드

설명

-(void)startAnimating

에니메이션을 개시함
(예)[ai startAnimating];

-(void)stopAnimating

에니메이션을 정지함
(예)[ai stopAnimating];

-(BOOL)isAnimating

에니메이션중인지 아닌지를 반환
(예)BOOL b = [ai 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];  // 에니메이션을 중지하고 싶을때 호출

 

 

NSURLRequestNSMutableURLRequest 차이점

  • NSMutableURLRequest 생성한 인스턴스의 할용도가 높다
  • NSMutableURLRequest post방식으로 전송가능
  • NSMutableURLRequest http헤더를 설정가능
Posted by 김반장78
,