是否有完整的示例使用所有NSURLConnection委托方法?

时间:2010-01-23 19:36:47

标签: iphone nsurlconnection

我很难找到NSURLConnection委托方法实现的任何示例。 Apple的SeismicXML示例不完整。例如,他们没有合并

-connection:willSendRequest:redirectResponse:

也许那里有好文。我已经完成了关于此的所有Apple资料。

1 个答案:

答案 0 :(得分:17)

这是我最近一直在使用的实现:

.h:
    NSMutableData *responseData;

.m:
    - (void)load {
        NSURL *myURL = [NSURL URLWithString:@""];
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:myURL
                                                 cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
                                             timeoutInterval:60];

    [[NSURLConnection alloc] initWithRequest:request delegate:self];
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    responseData = [[NSMutableData alloc] init];
}

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

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    [responseData release];
    [connection release];
    [textView setString:@"Unable to fetch data"];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection 
{
    NSLog(@"Succeeded! Received %d bytes of data",[responseData
                                                   length]);
    NSString *txt = [[[NSString alloc] initWithData:responseData encoding: NSASCIIStringEncoding] autorelease];

}