2

我正在处理一个连接到服务器并从中下载数据的项目。如果连接中断,我喜欢支持恢复下载。我的方法是将下载的数据部分保存到目标文件中;如果连接中断,我想使用 connection:didWriteData:totalBytesWritten:expectedTotalBytes 标记下载的部分,然后使用服务器从停止的部分恢复。

我的代码:

- (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");
}

我的问题是为什么永远不会调用“connection:didWriteData:totalBytesWritten:expectedTotalBytes”方法?

非常感谢!克里斯

4

2 回答 2

1

你有没有在.h文件中添加这个:

 @interface yourViewContoller : UIViewController <NSURLConnectionDataDelegate, NSURLConnectionDelegate>
于 2012-09-24T06:00:14.697 回答
0

根据苹果的文档

NSURLConnectionDownloadDelegate 协议描述了应该由使用 Newsstand Kit 的 downloadWithDelegate: 方法创建的 NSURLConnection 实例的委托来实现的方法。

此外,它还说:

如果你直接使用 NSURLConnection,你的委托类应该实现 NSURLConnectionDataDelegate 协议中定义的方法。

于 2013-09-27T08:49:16.417 回答