How to Download Image from the Web in iOS using Swift

How to Download Image from the Web in iOS using Swift

Today, I’m going to show you how to download an image from the Web(URL), on your iOS device using UIActivityViewController.

As an example, we are going to download the following image I found on the Internet and uploaded on imgur.com

https://i.imgur.com/yc3CbKN.jpg

Creating the Image Downloader (UIActivityViewController)

Go to your ViewController‘s swift file and create a method with a parameter url and type String.

Convert the URL String to URL.

Get the Data from the URL.

func downloadImage(url: String) {
        guard let imageUrl = URL(string: url) else { return }
        getDataFromUrl(url: imageUrl) { data, _, _ in
        
            //...
            
        }
    }

    func getDataFromUrl(url: URL, completion: @escaping (Data?, URLResponse?, Error?) -> ()) {
        URLSession.shared.dataTask(with: url) { data, response, error in
            completion(data, response, error)
        }.resume()
    }

Inside the getDataFromUrl closure, create an UIActivityViewController and pass the data from the URL.

func downloadImage(url: String) {
        guard let imageUrl = URL(string: url) else { return }
        getDataFromUrl(url: imageUrl) { data, _, _ in
            DispatchQueue.main.async() {
                let activityViewController = UIActivityViewController(activityItems: [data ?? ""], applicationActivities: nil)
                activityViewController.modalPresentationStyle = .fullScreen
                self.present(activityViewController, animated: true, completion: nil)
            }
        }
    }

Asking for Permissions

To download images on iOS, you need to ask the user first to give you access to save an image in their Photo library.

Go to Info.plist and press the + button.

In the new row, select Privacy – Photo Library Additions Usage Description from the drop-down list.

Add why the user needs to give this permission to your app.

In this example, we added ‘Permission required to save photos from the Web‘.

Using the Image Downloader

In your ViewController swift file use the image downloader by calling the method downloadImage and passing the url (string) of your image you want to download.

@IBAction func downloadButtonAction(_ sender: UIButton) {
    downloadImage(url: image)
}
You can find the final project here

Did you find this tutorial helpful?



If you have any questions, please feel free to leave a comment below

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments