Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I allow downloads from a WebView using the standard download system on a Mac app?

I am building a mac app and would like to able to include the ability to browse the web and download files from the sites using the standard downloads system like you see when using safari.

At the moment when I click a link to a .zip or .nzb in the app it does nothing! Is there a way of allowing this from the app?

Thanks in advance for any help :)

like image 939
Will Roberts Avatar asked Feb 01 '12 11:02

Will Roberts


1 Answers

The download manager in Safari is implemented by Safari, not by WebKit, so you don't get that functionality "for free", just the tools to build it.

In order to be able to download files, you need to assign an object as the WebPolicyDelegate of the WebView and implement the webView:decidePolicyForMIMEType:request:frame:decisionListener: delegate method.

In that method, you must call one of the WebPolicyDecisionListener protocol methods on the object that is passed as the decisionlistener parameter to the method. The three WebPolicyDecisionListener protocol methods are ignore, use or download. For any MIME types that you want to download, you must call download on the object passed as the listener parameter:

- (void)webView:(WebView *)webView 
   decidePolicyForMIMEType:(NSString *)type 
                   request:(NSURLRequest *)request 
                     frame:(WebFrame *)frame 
          decisionListener:(id < WebPolicyDecisionListener >)listener
{
    if([type isEqualToString:@"application/zip"])
    {
        [listener download];
    }
    //just ignore all other types; the default behaviour will be used
}

You then need to assign an object as the download delegate of your WebView. This object will be sent all of the NSURLDownloadDelegate protocol messages as well as the WebDownload delegate messages. You can use these messages to choose where the file is downloaded, as well as to implement a download manager UI like Safari.

like image 194
Rob Keniger Avatar answered Nov 01 '22 04:11

Rob Keniger