2011-11-07 7 views
13

これはadreesに私は、オブジェクトを送信しています。このような読むNSURLresponse

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response

NSlog(@"%@",response); Iこのコードを取得しています:

<NSHTTPURLResponse: 0x7d2c6c0> 何とか文字列を取得する必要があります。 どうすれば読むことができますか?

答えて

18

私はこの回答を別の質問に書いていますが、それはあなたに役立つと思います。方法

-(void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data

-(void) connectionDidFinishLoading:(NSURLConnection *)connection


-(void) requestPage 
{ 
    NSString *urlString = @"http://the.page.you.want.com"; 
    NSURL *url = [NSURL URLWithString:urlString]; 

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLCacheStorageAllowed timeoutInterval:20.0f]; 


    responseData = [[NSMutableData alloc] init]; 
    connection = [[NSURLConnection connectionWithRequest:request delegate:self] retain]; 
    delegate = target; 
} 


-(void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response 
{ 
    if ([response isKindOfClass:[NSHTTPURLResponse class]]) 
    { 
     NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*) response; 
     //If you need the response, you can use it here 
    } 
} 

-(void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data 
{ 
    [responseData appendData:data]; 
} 

-(void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error 
{ 
    [responseData release]; 
    [connection release]; 
} 

-(void) connectionDidFinishLoading:(NSURLConnection *)connection 
{ 
    if (connection == adCheckConnection) 
    { 
     NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding]; 

     //You've got all the data now 
     //Do something with your response string 


     [responseString release]; 
    } 

    [responseData release]; 
    [connection release]; 
} 
+0

の受信を開始できますが、複数の要求に対処する方法はありますか?たとえば、接続が進行中で、別の要求が接続の前に到着すると、応答データが解放される可能性があります。 – raghul

+0

@raghulはい、可能です。それを回避するために、私はおそらくクラス "ConnectionHandler"でこれをラップして、それぞれの接続が 'responseData'の独自のインスタンスを持つようにします –

6
NSHTTPURLResponse * httpResponse = (NSHTTPURLResponse *) response; 
int errorCode = httpResponse.statusCode; 
NSString *fileMIMEType = [[httpResponse MIMEType] lowercaseString]; 

詳細については、iOSドキュメント:NSHTTPURLResponseをご覧ください。

と患者のこと:すべての接続があなたがサブクラスを作成し、- (NSString*) descriptionメソッドをオーバーライドすることができNSHTTPURLResponse

+0

で特に見て、私は ... 200ウィッヒはokです取得していますが、どのように私はリンゴサーバを読むことができます応答? –

+0

200接続が正しく確立されたことを意味し、データ – Nekto

3

接続でデータが受信されることが予想される場合は、使用できます。

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data 

あなたは単にデータをNSStringに変換することができます。