Mekal Z

Mekal Z

A programmer running out of the wall.
twitter

How to download an image from the internet and save it locally in SwiftUI?

image

SwiftUI Development Notes

In SwiftUI, we can use URLSession to download images from the internet and use FileManager to save them locally. Here is an example code that demonstrates how to download and save an image in SwiftUI:

import SwiftUI

struct ContentView: View {
    @State private var image: UIImage?
    
    var body: some View {
        if let image = image {
            Image(uiImage: image)
                .resizable()
                .aspectRatio(contentMode: .fit)
        } else {
            Text("Loading...")
                .onAppear {
                    // Download and save the image
                    downloadImage(from: URL(string: "https://example.com/image.png")!) { result in
                        switch result {
                        case .success(let image):
                            saveImage(image, withName: "image.png")
                            self.image = image
                        case .failure(let error):
                            print(error.localizedDescription)
                        }
                    }
                }
        }
    }
    
    // Download an image from the specified URL and call the completion handler with the result
    func downloadImage(from url: URL, completion: @escaping (Result<UIImage, Error>) -> Void) {
        URLSession.shared.dataTask(with: url) { data, response, error in
            guard let data = data, let image = UIImage(data: data) else {
                completion(.failure(error ?? NSError(domain: "Unknown", code: 0)))
                return
            }
            completion(.success(image))
        }.resume()
    }
    
    // Save the specified image to the app's documents directory with the specified name
    func saveImage(_ image: UIImage, withName name: String) {
        guard let data = image.pngData(),
              let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else {
            return
        }
        let fileURL = documentsDirectory.appendingPathComponent(name)
        do {
            try data.write(to: fileURL)
        } catch {
            print(error.localizedDescription)
        }
    }
}

In the above code, we use the @State property wrapper to store the downloaded image. In the view, we first check if the image has been downloaded, and if so, display it in an Image view. Otherwise, we display the text "Loading..." and call the downloadImage method in the onAppear modifier to download the image. Once the image is downloaded, we save it locally using the saveImage method and then set it to the @State property to display it in the Image view.

In the downloadImage method, we use URLSession to download the image and pass the result as a Result type to the completion handler. In the saveImage method, we use FileManager to save the image locally. Note that here we save the image as a PNG format, but you can also save it in other formats (e.g., JPEG).

Please note that when saving the image using FileManager, you should always use the URL of the application's document directory. In this example, we use FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first to get the URL of the document directory.

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.