views:

420

answers:

3

Hi,

I am currently developing an iPhone app and would like to implement the ability to download files (specifically pdf, mp3, doc and ppt files) 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.

Any advice/links to tutorials etc would be much appreciated.

Cheers

+3  A: 

Edited
UIWebView can not be used to download pdf, mp3, doc, ppt, etc... It is used to display only webpage.

You need to use Quartz 2D to draw pdf document. You need Media Player framework to to play songs, audio books.

To download a file from the server, you can try to use [NSData initWithContentsOfURL] method.

An example:

NSString *strImagePathURL = [NSString stringWithFormat:@"http://foo.com/%d.png", item];
NSData *imageData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:strImagePathURL]];

You can later decide what to do with NSData, you can save it to file on the Documents folder using the [NSData writeToFile] method.

sfa
Thanks for the answer, but if you read the question I ask how to download them from the internet using the UIWebView. The question was more a case of how to capture links to files with the stated file extensions.
Jack
Also you can handle mp3s and pdfs in a UIWebView.
Jack
hi Jack, if you want to download the files of specific types, you still need to handle yourself. From what I know, saving files in Safari is impossible. You can capture the links that user click and create the NSData to download them manually.
sfa
+2  A: 

Have found the method for capturing links. It's a delegate method, so make sure that all of the hooks are in place:

- (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType {

    //CAPTURE USER LINK-CLICK.
    if (navigationType == UIWebViewNavigationTypeLinkClicked) {
        NSURL *URL = [request URL]; 
        NSLog(@"url is: %s ", URL);
    }   
    return YES;   
}

From here

Will post my final code once I'm done.

Jack
+1  A: 
  1. To capture links in a UIWebView, implement the webView:shouldStartLoadWithRequest:navigationType: delegate method, and return NO when you see a link you want to handle.

  2. For example code on how to download using HTTP on the iPhone, see the SimpleURLConnections sample project.

Tobias Cohen