iphone - NSURLConnection 下载委托(delegate)方法未被调用

标签 iphone ios xcode nsurlconnection

我正在开发一个连接到服务器并从中下载数据的项目。如果连接中断,我喜欢支持恢复下载。我的方法是将下载的数据部分保存到目标文件中;如果连接中断,我想使用 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”方法从未被调用过?

非常感谢! 克里斯

最佳答案

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

 @interface yourViewContoller : UIViewController <NSURLConnectionDataDelegate, NSURLConnectionDelegate>

关于iphone - NSURLConnection 下载委托(delegate)方法未被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12558484/

相关文章:

iphone - 两个可见的 CATiledLayers 引起了问题!

ios - 拦截来电ios sdk(非越狱)

iphone - UISegmentedControl:ValueChanged 处理程序上的 EXC_BAD_ACCESS

ios - 使用对 SPPlaylistFolder 的folderId 引用

ios - 我应该为 Pod 使用 Swift 4 迁移工具吗?

ios - swift NSDate ISO 8601 格式

swift - 为什么我的 avfoundation swift3 不起作用

iphone - Phonegap-无法从JavaScript调用本地iOS功能

objective-c - xcode ios : in cell image overlaps on the label

ios - 如何在快速更改屏幕方向时避免背景图像平铺