Use Image in SwiftUI with either URL or Data without UIKit

Viewed 257

I have downloaded an image in bytes (Data). I stored it with FileManager in the cache of the user's device. I was wondering if I could create an Image with either Data or a local URL, I am currently using UIImage but I want to support macOS.

Is there a full SwiftUI way of creating an Image with URL or Data without UIKit/UIImage?

1 Answers

if your question is about showing and image in macos, that you already have downloaded (and is in the cachesDirectory), then try something like this, to create an image from your image in bytes: (using NSImage for macos)

struct ContentView: View {
    @State var img = NSImage()
    
    var body: some View {
        Image(nsImage: img)
            .onAppear {
                do {
                    // local file
                    let url = try FileManager.default
                        .url(for: .cachesDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
                        .appendingPathComponent("kat")  // <--- your file name here
                        .appendingPathExtension("png")
                    
                    print("----> url: \(url)")
                    
                    // even from the net
//                    let url = URL(string: "https://upload.wikimedia.org/wikipedia/commons/e/ef/Red-billed_gull%2C_Red_Zone%2C_Christchurch%2C_New_Zealand.jpg")!
                    
                    if let nsimg = NSImage(contentsOf: url) { img = nsimg }
                } catch {
                    print("\(error)")
                }
            }
    }
    
}
Related