IOS NSURLConnection does not download files from specific URLs

I have an NSURLConnection in a subclass of a tableview cell that can load most files. I noticed, however, that some cannot start the download and time out. An example would be this URL, which is just a test zip file that loads perfectly in any other browser. Here is my download code

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

Does anyone see anything that can cause this?

Gets an error:

 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."} 
+6
source share
7 answers

"I have an NSURLConnection in a subclass of a tableview cell" - never do this. As Sung-Pil Lim already pointed out, TableView cells will be reused, which can cause this problem.

In any case, the response data of your connection is a property of the model. A model can encapsulate how it gets to this data. If this data is not available immediately after it is accessed, it should specify the value "placeholder" instead and run an asynchronous task that retrieves this data.

Suppose a model property, an image, is available to the view controller so that it is displayed in the view. The model has not yet uploaded its actual image - and thus it returns a “placeholder image” to allow the display of something. But at the same time, the model launches an asynchronous task to load the image. When this connection finishes loading data, the model updates the internal property, thereby replacing the placeholder with a real image. Property updating should be done in the main thread - because UIKit views can access the same property.

During initialization, the view controller is registered as an observer of the model property (see KVO). When the model property is updated, the controller receives a notification. Then, the view controller takes appropriate action so that the view is redrawn and displays the new updated value.

Your model should have a “cancel” method, which will be sent to the model from the controller when the actual value of the model property is no longer required. For example, the user switched to another view (see ViewWillDisappear).

+3
source

I tried your codes.

 - (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 

Works ... on ViewController

A "request timeout error" was connected to a network connection. or...

Do you implement a UITableViewCell? If you initialize cell reuse codes, refer to the connection. maybe trouble. I just thought.

If you add more of your codes. May I help you more than that.

+2
source

I would start from scratch and just use the base code to work with the download. Download a lot of NSLog (s) to track everything. If this works, continue to add your code and see if you stumbled on an error. I suggest the basic NSURLConnection code:

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

try with HCDownloadViewController and you can check which url is not loaded. and next time sync for that particular url that is not loaded.

.h file

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

.m file

 #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

0
source

accept any response with an HTTP response code 200-299 and disable caching on the http connector.

0
source

double check that your url is compliant with RFC 2396. therefore it should include HTTP: //

-1
source

Do you have any libraries (TestFlight, UA, etc.) in the project? Try removing them and re-checking. We had an application that used NSUrlConnection with the TestFlight SDK, which caused all kinds of sporadic network problems.

NSURLConnection timeout

ASIHTTPRequest Request Timeout

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

-1
source

Source: https://habr.com/ru/post/944002/


All Articles