Skip to content
Branch: master
Find file History
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Type Name Latest commit message Commit time
..
Failed to load latest commit information.
Images reorganizing files into recipes folder Mar 7, 2018
Resources/Images.xcassets/LaunchImage.launchimage reorganizing files into recipes folder Mar 7, 2018
50_icon.png
AppDelegate.cs reorganizing files into recipes folder Mar 7, 2018
DownloadImage.csproj reorganizing files into recipes folder Mar 7, 2018
DownloadImage.sln reorganizing files into recipes folder Mar 7, 2018
DownloadImageViewController.cs
Info.plist reorganizing files into recipes folder Mar 7, 2018
README.md

README.md

id title brief article
47F1C480-5914-2C3D-B7F0-FF6CE66DDFC1
Download an Image
This recipe shows how to download an image file using the WebClient class in Xamarin.iOS.

Recipe

To download a text file follow these steps:

  • Add a new using statements to your code:
using System.Net;
using System.IO;
using System.Text;
  • Create a WebClient object:
var webClient = new WebClient();
  • Add an event handler that will execute when the download is complete. First it retrieves the downloaded text to a variable, then it creates a local file path and finally it saves the file to local storage:
webClient.DownloadDataCompleted += (s, e) => {
    var bytes = e.Result; // get the downloaded data
    string documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
    string localFilename = "downloaded.png";
    string localPath = Path.Combine (documentsPath, localFilename);
    File.WriteAllBytes (localPath, bytes); // writes to local storage
};
  • Create the Url for the file to download:
var url = new Uri("https://www.xamarin.com/content/images/pages/branding/assets/xamagon.png");
  • Finally trigger the download itself (when complete, the handler we defined in step 3 will execute):
webClient.DownloadDataAsync(url);

Additional Information

The sample code looks like this screenshot when the file has been successfully downloaded. The alert and text view are populated by adding the following code to the completion handler defined in Step 3:

InvokeOnMainThread (() => {
    textView.Text = text;
    new UIAlertView ("Done", "Image downloaded and saved", null, "OK", null).Show();
});

Notice that all interactions with UI controls is done within an InvokeOnMainThread method call. This is because the file download occurs asynchronously (in a background thread), and background threads aren’t allowed to access the UI directly.

You can’t perform that action at this time.