iOS NSURLConnection不从某些URL下载文件

Chr*_*nam 6 objective-c nsurlconnection ios

我有NSURLConnection一个tableview单元子类,可以下载大多数文件.但是,我注意到有些人无法开始下载,并且超时.一个例子是这个 URL,它只是一个测试zip文件,可以在任何其他浏览器中正常下载.下载我的代码

-(void)downloadFileAtURL:(NSURL *)url{
    self.downloadedData = [[NSMutableData alloc] init];
    self.url = url;
    conn = [[NSURLConnection alloc] initWithRequest:[NSURLRequest requestWithURL:self.url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:1200.0] delegate:self startImmediately:YES];
}

- (void)connection:(NSURLConnection*)connection didReceiveResponse:(NSHTTPURLResponse*)response
{
    int statusCode = [response statusCode];
    if (statusCode == 200){
        self.fileName.text = response.URL.lastPathComponent;
        self.respo = response;
        expectedLength = [response expectedContentLength];
    }
}

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

- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
    CFStringRef mimeType = (__bridge CFStringRef)[_respo MIMEType];
    CFStringRef uti = UTTypeCreatePreferredIdentifierForTag(kUTTagClassMIMEType, mimeType, NULL);
    CFStringRef extension = UTTypeCopyPreferredTagWithClass(uti, kUTTagClassFilenameExtension);
    NSString *fileName = [NSString stringWithFormat:@"%@.%@", [[_respo suggestedFilename] stringByDeletingPathExtension], (__bridge NSString *)extension];
    [[NSFileManager defaultManager] createFileAtPath:[[self docsDir] stringByAppendingPathComponent:[NSString stringWithFormat:@"Downloads/%@", fileName]] contents:_downloadedData attributes:nil];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
    NSLog(@"Download failed with error: %@", error);
}
Run Code Online (Sandbox Code Playgroud)

有人看到任何可能导致这种情况的事吗?

继承人错误:

Error Domain=NSURLErrorDomain Code=-1001 "The request timed out." UserInfo=0x1fd2c650 
{NSErrorFailingURLStringKey=http://download.thinkbroadband.com/10MB.zip, 
NSErrorFailingURLKey=http://download.thinkbroadband.com/10MB.zip, 
NSLocalizedDescription=The request timed out., NSUnderlyingError=0x1fdc90b0 "The request timed out."}
Run Code Online (Sandbox Code Playgroud)

Cou*_*per 3

“我在 tableview 单元格子类中有一个 NSURLConnection ” - 永远不要这样做。正如 Sung-Pil Lim 已经正确指出的那样,TableView 单元格将被重用,这可能会导致此问题。

无论如何,连接的响应数据是模型的属性。该模型可能会封装它如何获取这些数据。如果该数据在被访问后不能立即可用,则应该提供一个“占位符”值,并启动一个异步任务来检索该数据。

假设模型的属性(图像)将由视图控制器访问,以便由视图显示。该模型尚未加载其实际图像 - 因此它返回一个“占位符图像”以便让视图显示某些内容。但同时模型正在启动异步任务来加载图像。当此连接完成数据加载时,模型会在内部更新其属性 - 从而用真实图像替换占位符。属性的更新应该在主线程上执行 - 因为 UIKit 视图也可以访问相同的属性。

在初始化期间,视图控制器已注册为模型属性的观察者(请参阅 KVO)。当模型的属性更新时,控制器会收到通知。然后视图控制器执行适当的操作,以便重新绘制视图并显示新的更新值。

您的模型应该有一个“取消”方法,当不再需要模型属性的实际值时,该方法将从控制器发送到模型。例如,用户切换到另一个视图(参见 viewWillDisappear)。