Download Images With .NET For iOS

One of the main advantages of using .NET for iOS is that we can take advantage of the knowledge of C# in the iOS operating system. In this example we will carry out the coding to be able to download an image from the internet, save it locally on the iPhone and load it to the graphical interface, in a process very similar to the one carried out for Android in my article:

Beginnings Of Xamarin Android For Developers Of Android Studio (c-sharpcorner.com)

For this example it is important that we can create a .NET for iOS type application in Visual Studio for Mac, to prepare the environment I suggest you first take a look at the article that I mention below so that you can create the Application using the XCode graphical interface: Create Apps for iOS with .NET 7 (c-sharpcorner.com)

Now, we proceed to the .NET for iOS application:

Step 1

We create the graphic interface in XCode with the following structure, an ImageView type object and a Button type object, which will have the names “Img” and “btnDownload”, and we save the interface.

Download Images with .NET for iOS

Step 2

In Visual Studio for Mac we verify that our Interface loads correctly in the iOS simulator.

Download Images with .NET for iOS

Step 3

We add the System.Net and System.Net.Mime.MediaTypeNames; libraries, we also declare a variable called “pathios” and another that will be an AlertController called “Alert”. In the ViewDidLoad method we place the call to the “ColocarImagen” event when the button is pressed.

using static System.Net.Mime.MediaTypeNames;
using System.Net;
namespace iOSNetDescargarImagen;

public partial class ViewController : UIViewController
{
    string pathios;
    UIAlertController Alert;
    public ViewController () : base (nameof (ViewController), null)
	{
    }
    public ViewController(IntPtr handle) : base(handle)
    {
    }

    public override void ViewDidLoad ()
	{
		base.ViewDidLoad ();
        btnDownload.TouchUpInside += ColocarImagen;
    }
}

Step 4

We generate the "ColocarImagen" event where we call the method that will be in charge of downloading the image and placing it in the ImageView object, we also call a method called MessageBox in the catch and where we will pass the parameters in case an error occurs.

async void ColocarImagen(object sender, EventArgs e)
{
    try
    {
        var path = await DownloadImage();
        Img.Image = UIImage.FromFile(path);
    }
    catch (Exception ex)
    {
        MessageBox("Error", ex.Message);
    }
}

Step 5

We generate the asynchronous event "DownloadImage" which enables a Web client that will perform the asynchronous download of the image that is placed in the URL, which will be saved in a byte array, then a folder will be generated inside the device in the special folder of the application, the name that the file will have is assigned and the Path.Combine is used to generate the final path with the name of the file, and with the File.WriteAllBytes the file is generated with the content of the array of bytes and the path defined, finally the route of the method is extracted, in case of an error the route is captured and cleaned.

public async Task<string> DownloadImage()
{
    try
    {
        var client = new WebClient();
        byte[] imgurl = await client.DownloadDataTaskAsync
            ("https://pbs.twimg.com/media/D1-T4fqXcAUhCW7.jpg");
        var folder = System.Environment.GetFolderPath
            (System.Environment.SpecialFolder.Personal);
        var filename = "Imagen.jpg";
        pathios = Path.Combine(folder, filename);
        File.WriteAllBytes(pathios, imgurl);
        return pathios;
    }
    catch (Exception ex)
    {
        MessageBox("Error", ex.Message);
        pathios = null;
        return pathios;
    }
}

Step 6

We generate the error method called “MessageBox” where we enable an AlertController, add the button text to it, and display it in the current View.

public void MessageBox(string titulo, string message)
{
    Alert = UIAlertController.Create(titulo, message,
        UIAlertControllerStyle.Alert);
    Alert.AddAction(UIAlertAction.Create("Done",
        UIAlertActionStyle.Default, null));
    PresentViewController(Alert, true, null);
}

Complete Code

using static System.Net.Mime.MediaTypeNames;
using System.Net;
namespace iOSNetDescargarImagen;

public partial class ViewController : UIViewController
{
    string pathios;
    UIAlertController Alert;
    public ViewController () : base (nameof (ViewController), null)
	{
    }
    public ViewController(IntPtr handle) : base(handle)
    {
    }

    public override void ViewDidLoad ()
	{
		base.ViewDidLoad ();
        btnDownload.TouchUpInside += ColocarImagen;
    }
    async void ColocarImagen(object sender, EventArgs e)
    {
        try
        {
            var path = await DownloadImage();
            Img.Image = UIImage.FromFile(path);
        }
        catch (Exception ex)
        {
            MessageBox("Error", ex.Message);
        }
    }
    public async Task<string> DownloadImage()
    {
        try
        {
            var client = new WebClient();
            byte[] imgurl = await client.DownloadDataTaskAsync
                ("https://pbs.twimg.com/media/D1-T4fqXcAUhCW7.jpg");
            var folder = System.Environment.GetFolderPath
                (System.Environment.SpecialFolder.Personal);
            var filename = "Imagen.jpg";
            pathios = Path.Combine(folder, filename);
            File.WriteAllBytes(pathios, imgurl);
            return pathios;
        }
        catch (Exception ex)
        {
            MessageBox("Error", ex.Message);
            pathios = null;
            return pathios;
        }
    }
    public void MessageBox(string titulo, string message)
    {
        Alert = UIAlertController.Create(titulo, message,
            UIAlertControllerStyle.Alert);
        Alert.AddAction(UIAlertAction.Create("Done",
            UIAlertActionStyle.Default, null));
        PresentViewController(Alert, true, null);
    }
}

Step 7

We run the application, we click it and that's it, the image is downloaded to the device, and it is loaded in the ImageView that we have in the Graphical Interface.

With this we can download images to the device and be able to view them using .NET for iOS from Visual Studio for Mac.

Download Images with .NET for iOS

Thank you very much.


Similar Articles