Search code examples
fileuiwebviewdownloadnsdata

UIWebView Link Delegate


What I'm trying to do is create an app that will download files of certain extensions (let's say a .mp3 file from my FTP). I want a delegate method for tapping a link in a UIWebview, and if the link ends in ".mp3", create some sort of download method that would write the file to the /Documents directory with an automatic file name.

Is there any way to achieve this? I've looked everywhere for downloading files and writing them to the /Documents directory but no answers.

Thanks in advance!


Solution

  • Yes there is:

          - (void)webViewDidFinishLoad:(UIWebView *)aWebView
            {
                currentURL = self.webView.request.URL.absoluteString;
                NSLog(@"Current URL %@", currentURL);
                if ([currentURL rangeOfString:@"mp3"].location == NSNotFound) {
                    NSLog(@"string does not contain mp3");   
                } else {
                    NSLog(@"Found mp3");
                    //Do the download here
    NSString *urlString = currentURL;
                NSURL  *url = [NSURL URLWithString:urlString];
                NSData *urlData = [NSData dataWithContentsOfURL:url];
                [urlData writeToURL:url atomically:YES];
                if ( urlData )
                {  
                    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
                    NSString  *documentsDirectory = [paths objectAtIndex:0];
    
                    NSString  *filePath = [NSString stringWithFormat:@"%@/%@", documentsDirectory,@"downloadedMP3.mp3"];
                    [urlData writeToFile:filePath atomically:YES];
                }
                }
            }
    

    Don't forget to conform to the UIWebView protocol in your .h file (<UIWebViewDelegate>)