NSURLConnection connection:didReceiveData: is not

2019-05-22 16:50发布

问题:

A weird problem. I wanna load an image from web, so i use NSURLConnection to do it. Everything is ok when i do testing my code on ios4.3. But when i'm launch my app on ios5.0, i found the connection:didreceiveData haven't been called whatever what i did. otherelse functions is called normally, just like connectionDidFinishLoading in ios4.3 and connectionDidFinishDownloading in ios5.0. so u guys, who can help me, thanks advanced!

-(void)load
{
    if(isDownloading){
        return;
    }
    if(conn != nil){
        [conn release];
    }
    if(data != nil){
        [data release];
        data = nil;
    }
    [self isDownloading:YES];
    ImageDownloadData* imageDownloadData = [imageList objectAtIndex:count];
    NSURL* url = [imageDownloadData url];
    NSURLRequest* request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
    conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    if(conn){
        [conn start];
    }
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)rd
{
    NSLog(@"data");
    if(!data){
        data = [[NSMutableData alloc] initWithData:rd];
        return;
    }
    [data appendData:rd];
}

回答1:

I can't be sure if this is the same problem you're having, but I had a similar issue, and resolved it by taking out the in methods and references to NSURLConnectionDownloadDelegate. Apparently delegates of NSURLConnection can only implement one of the two protocols that are derived from NSURLConnectionDelegate at a time.

There's been some odd API changes between 4.3 and 5.0. Apple changed the NSURLConnectionDelegate from an informal protocol to a formal one, and branched out some of the methods into two additional subprotocols: NSURLConnectionDataDelegate and NSURLConnectionDownloadDelegate. (Oddly though, they depreciated the identical methods in NSURLConnectionDelegate but didn't document where they moved to.)

I've been noticing when compiling my code against the 6.0 API that I've been having trouble getting Cocoa Touch to call connection: didReceiveData: if I Implement methods from both NSURLConnectionDataDelegate and NSURLConnectionDownloadDelegate. All the other methods I implemented were called as expected.