iOS NSURLConnection不从某些URL下载文件

我有一个NSURLConnection在一个tableview单元格的子类,可以下载大部分文件。 然而,我注意到,有些未能开始下载,并超时。 一个例子就是这个 URL,它只是一个testingzip文件,可以在任何其他浏览器下载。 下载我的代码

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

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

inheritance人错误:

 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."} 

“我有一个tableview单元格子类NSURLConnection” – 从来没有这样做。 正如Sung-Pil Lim已经正确指出的那样,TableView Cells将被重用,这可能会导致这个问题。

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

假设一个模型的属性,一个图像,将被视图控制器访问,以便被视图显示。 该模型还没有加载它的实际图像 – 因此它返回一个“占位符图像”,以便让视图显示一些东西。 但同时该模型正在启动一个asynchronous任务来加载图像。 当这个连接完成加载数据时,模型在内部更新它的属性 – 从而用实际图像replace占位符。 属性的更新应该在主线程上执行 – 因为UIKit视图也可以访问相同的属性。

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

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

我试过你的代码

 - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{ [self.downloadedData appendData:data]; NSLog(@"%d", data.length); } 2013-05-04 01:51:13.811 SomethingTodo[2732:c07] 1124 2013-05-04 01:51:13.856 SomethingTodo[2732:c07] 1448 2013-05-04 01:51:14.075 SomethingTodo[2732:c07] 1448 2013-05-04 01:51:17.180 SomethingTodo[2732:c07] 1448 2013-05-04 01:51:17.295 SomethingTodo[2732:c07] 1448 

它在ViewController上工作

'请求超时错误'被带到networking连接。 要么…

你在调用UITableViewCell吗? 如果初始化单元重用代码处理连接。 也许会带来麻烦。 只是我想。

如果你附加更多的代码。 我可以帮你吗?

我会从一个干净的石板开始,只是使用基本代码来下载。 加载大量的NSLog来跟踪一切。 如果可行,请继续添加自定义代码,看看是否遇到错误。 我build议基本的NSURLConnection代码:

 -(void)startDownloading:(NSString *)URLaddress{ NSLog(@"start downloading from: %@",URLaddress); NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:[URLaddress stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding]] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0]; __unused NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self startImmediately:YES]; } - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{ NSLog(@"didReceiveResponse: %@", response); } - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{ NSLog(@"didReceiveData"); } - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{ NSLog(@"Connection failed! Error - %@ %@",[error localizedDescription], [[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]); } - (void)connectionDidFinishLoading:(NSURLConnection *)connection{ NSLog(@"connectionDidFinishLoading"); } 

尝试使用HCDownloadViewController,你可以检查哪个url没有被下载。 并下一次同步该特定的URL不下载。

.h文件

 #import "HCDownloadViewController.h" @interface HomeViewController_iPhone : UIViewController<HCDownloadViewControllerDelegate> { HCDownloadViewController *tblDownloadHairStyle; } @property (nonatomic,retain) HCDownloadViewController *tblDownloadHairStyle; 

.m文件

 #define kAppDirectoryPath NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) 

@synthesize tblDownloadHairStyle

 - (void)viewDidLoad { [super viewDidLoad]; tblDownloadHairStyle=[[HCDownloadViewController alloc] init]; tblDownloadHairStyle.delegate=self; } - (void)connection:(NSURLConnection*)connection didReceiveResponse:(NSHTTPURLResponse*)response { [self createDocumentDirectory:@"Downloaded_HairStyle"]; NSString *pathHair=[self getDocumentDirectoryPath:@"Downloaded_HairStyle"]; tblDownloadHairStyle.downloadDirectory = pathHair; ////You can put url in for loop, it create queue for downloading. [tblDownloadHairStyle downloadURL:[NSURL URLWithString:@"yourUrl"] userInfo:YourResponseDictonary]; } -(void)createDocumentDirectory:(NSString*)pStrDirectoryName { NSString *dataPath = [self getDocumentDirectoryPath:pStrDirectoryName]; if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath]) [[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:NULL]; } -(NSString*)getDocumentDirectoryPath:(NSString*)pStrPathName { NSString *strPath = @""; if(pStrPathName) strPath = [[kAppDirectoryPath objectAtIndex:0] stringByAppendingPathComponent:pStrPathName]; return strPath; } #pragma mark- #pragma mark-HCDownloadViewController Delegate Method - (void)downloadController:(HCDownloadViewController *)vc startedDownloadingURL:(NSURL *)url userInfo:(NSDictionary *)userInfo { } - (void)downloadController:(HCDownloadViewController *)vc finishedDownloadingURL:(NSURL *)url toFile:(NSString *)fileName userInfo:(NSDictionary *)userInfo { if (vc==tblDownloadHairStyle) { if ([tblDownloadHairStyle numberOfDownloads]==0) { NSLog(@"AllDownLoad are complete"); } } } - (void)downloadController:(HCDownloadViewController *)vc failedDownloadingURL:(NSURL *)url withError:(NSError *)error userInfo:(NSDictionary *)userInfo { NSLog(@"failedDownloadingURL=%@",url); } 

https://github.com/H2CO3/HCDownload

接受http响应代码范围为200-299的任何响应,并禁用http连接器上的caching。

仔细检查你的url地址是否符合RFC 2396,所以它必须包含HTTP://

项目中是否有任何库(TestFlight,UA等)? 尝试删除它们并重新testing。 我们有一个使用NSUrlConnection与TestFlight SDK的应用程序,导致各种零星的networking问题。

NSURLConnection超时

ASIHTTPRequest请求超时

https://github.com/AFNetworking/AFNetworking/issues/307