简体   繁体   中英

NSURLConnectionDownloadDelegate method not getting called

im working on a project that connect to server and download data from it. i like to support resume download if connection gets interrupt. my approach is to save the downloaded portion of data to a destination file; and if connection gets interrupted, i want to mark the downloaded portion using connection:didWriteData:totalBytesWritten:expectedTotalBytes and later resume from the stopped portion with server.

my code:

- (IBAction)connectToServer:(UIButton *)sender
{
    // setup url and send request to server
    NSURL *url = [NSURL URLWithString:BASED_URL];
    self.urlRequest = [[NSMutableURLRequest alloc] initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
    self.urlConnection = [[NSURLConnection alloc] initWithRequest:self.urlRequest delegate:self];

    // start receive data if connection established
    if (self.urlConnection){
    self.receivedData = [NSMutableData data];
    NSLog(@"starting to receive data");

} else {
    // handle error
    NSLog(@"failed to connect to server");
    }
}

- (void)doSomethingWithData
{
    // handle data here
}


#pragma NSURLConnectionDataDelegate

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse     *)response
{
    [self.receivedData setLength:0];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    // received data
    [self.receivedData appendData:data];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    // error connection
    NSLog(@"connection failed");
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSLog(@"Data receiving succeed, received: %d bytes of data", [self.receivedData length]);

}

- (void)connection:(NSURLConnection *)connection didWriteData:(long long)bytesWritten totalBytesWritten:(long long)totalBytesWritten expectedTotalBytes:(long long)expectedTotalBytes
{
    NSLog(@"not getting called");
}

my question is how come the "connection:didWriteData:totalBytesWritten:expectedTotalBytes" method never get called?

thanks so much! chris

您是否已将其添加到.h文件中:

 @interface yourViewContoller : UIViewController <NSURLConnectionDataDelegate, NSURLConnectionDelegate>

According to Apple's documentation :

The NSURLConnectionDownloadDelegate protocol describes methods that should be implemented by the delegate of instances of NSURLConnection created using Newsstand Kit's downloadWithDelegate: method.

Also, it says:

If you are using NSURLConnection directly, your delegate class should instead implement the methods defined in the NSURLConnectionDataDelegate protocol.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM