I am new to iPhone,
I am currently developing an iPhone app and would like to implement the ability to download file from the internet. I have created the UIWebView, but want to know the best way of capturing the files when they are linked to in the webview and then download them to a specified folder in the documents directory.
Here is my code snippet,
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[self.fileData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data1
{
[self.fileData appendData:data1];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
[activityIndicator stopAnimating];
activityIndicator.hidden=TRUE;
}
- (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType {
url = [request URL];
//CAPTURE USER LINK-CLICK.
NSString *file = [NSString stringWithString:[url absoluteString]];;
NSURL *fileURL = [NSURL URLWithString:file];
NSURLRequest *req = [NSURLRequest requestWithURL:fileURL];
[NSURLConnection connectionWithRequest:req delegate:self];
data = [NSData dataWithContentsOfURL:url];
//Saving file at downloaded path.
DirPath = [DestPath stringByAppendingPathComponent:[url lastPathComponent]];
[data writeToFile:DirPath atomically:YES];
UIAlertView* Alert = [[UIAlertView alloc] initWithTitle:@"Download Complete !"
message:nil delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[Alert show];
[Alert release];
return YES;
}
Problem is where to write condition, if my downloading gets failed and also i am getting Warning in my log shows : “wait_fences: failed to receive reply: 10004003”
It seems like you’re doing the same thing multiple times in this code. For example, you create a new NSURLRequest object even though one was already passed inside of the delegate method? You also run the synchronous dataWithContentsOfURL method after creating a new NSURLConnection? You also append some data into a property only to do nothing with that property?
What you probably want to do is create a new asynchronous NSURLConnection when the UIWebView should load. From there, allow the UIWebView to load that page. Inside of your delegate methods, instead of appending the data to some property, append the downloaded data to a file. When the connection finishes downloading, present your alert informing the user that the data was downloaded and saved.