▼iPhoneプログラミングメモ▼
HTTP通信

HTTP通信を行うプログラムを作成する。


テキストの準備

ネット上に配置。文字コードはUTF-8。
test.txt
これはテストです。


ソースコードの記述
HttpEx.h
#import <UIKit/UIKit.h>

//HttpExの宣言
@interface HttpEx : UIViewController <UITextFieldDelegate> {
    UITextField*             _textField;
    UIActivityIndicatorView* _indicator;
    NSMutableData*           _data;
}
@end

HttpEx.m
#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];
}

//データ受信開始時に呼ばれる
- (void)connection:(NSURLConnection*)connection
    didReceiveResponse:(NSURLResponse*)response {
    if (_data!=nil) [_data release];
    _data=[[NSMutableData data] retain];
}

//データ受信時に呼ばれる
- (void)connection:(NSURLConnection*)connection
    didReceiveData:(NSData*)data {
    [_data appendData:data];
}

//データ受信完了時に呼ばれる
- (void)connectionDidFinishLoading:(NSURLConnection*)connection {
    _textField.text=[self data2str:_data];
    
    //変数の解放
    [_data release];
    _data=nil;

    //インジケーターのアニメーションの停止
    [_indicator stopAnimating];
}

//データ受信失敗時に呼ばれる
- (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



−戻る−