阅读NSURLresponse

时间:2011-11-07 13:05:39

标签: ios objective-c xcode cocoa-touch nsurlconnection

我正在向此广告发送一个对象:https://sandbox.itunes.apple.com/verifyReceipt

NSUrlconnection 我试图用这种委托方法阅读它:

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response 像这样:

NSlog(@"%@",response); 我收到这段代码:

<NSHTTPURLResponse: 0x7d2c6c0> 我需要以某种方式得到一个字符串。 我怎么读呢?

4 个答案:

答案 0 :(得分: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];
}

答案 1 :(得分:6)

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

有关详细信息,请查看iOS文档:NSHTTPURLResponse

请耐心等待:并非所有联系都返回NSHTTPURLResponse

答案 2 :(得分:3)

如果您希望连接正在接收某些数据,则可以使用。

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

然后,您只需将数据转换为NSString

答案 3 :(得分:1)

您可以创建子类并覆盖- (NSString*) description方法。