NSMutableData *receivedData; //非同期通信 - (void)startConnection{ NSURL *url = [NSURL URLWithString:@"http://xxxx.jp/"]; NSURLRequest *request=[NSURLRequest requestWithURL:url]; NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES]; if (!connection) { //エラー } } //通信開始 - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { receivedData = [[NSMutableData data] retain]; } //通信中(何度も呼ばれる) - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{ // データを追加する [receivedData appendData:data]; } //通信終了 - (void)connectionDidFinishLoading:(NSURLConnection *)connection { NSString *dataStr = [[[NSString alloc] initWithData:receivedData encoding:NSUTF8StringEncoding] autorelease]; //受信データをログに表示 NSLog(@"%@", dataStr); [receivedData release]; receivedData = nil; [connection release]; } //通信エラー - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { //アラートを出す NSString *erroMessage = [error localizedDescription]; UIAlertView *alert = [[[UIAlertView alloc] initWithTitle:@"Error" message:erroMessage delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil] autorelease]; [alert show]; }
2013年10月23日水曜日
非同期通信
登録:
コメントの投稿 (Atom)
0 件のコメント:
コメントを投稿