Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

You can save files from a Xamarin.Forms WebView in iOS using the following steps:

  1. Enable the AllowFileAccessFromFileURLs property in your info.plist file. This allows your app to access local files from the WebView.
  2. Implement the DownloadStarted event in your WebView so that you can intercept the URL of the file being downloaded.
  3. Use the NSUrlSessionDownloadTask class to download the file to a local folder on the device.

Here is the sample code:

  1. Add the following key to your info.plist file:
<key>NSAppTransportSecurity</key>
    <dict>
        <key>NSAllowsArbitraryLoads</key> <true/>
    </dict>
<key>NSAllowsArbitraryLoads</key>
    <true/>
  1. Add an event handler for the DownloadStarted event in your WebView:
webView.DownloadStarted += WebView_DownloadStarted;

private void WebView_DownloadStarted(object sender, DownloadEventArgs e)
{
    // intercept file download URL and download file
    DownloadFile(e.Url);
}
  1. Use the NSUrlSessionDownloadTask class to download the file:
private async void DownloadFile(string url)
{
    var filename = Path.GetFileName(url);

    using (var client = new HttpClient())
    {
        var bytes = await client.GetByteArrayAsync(url);

        var documents = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
        var filepath = Path.Combine(documents, filename);

        File.WriteAllBytes(filepath, bytes);

        // show alert that file has been downloaded
        var alert = UIAlertController.Create("Download Complete",
            $"File '{filename}' has been saved to '{documents}'", UIAlertControllerStyle.Alert);
        alert.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null));

        PresentViewController(alert, true, null);
    }
}