norains
norains

Reputation: 773

How could Image view display photo by URL in SWiftUI?

How could Image view display photo by URL in SWiftUI?

I have a photo named "0.jpg" in my iPhone, and the URL is "/var/mobile/Containers/Data/Application/EB3DA19A-F7B2-48DD-8681-139C7FCB9090/Documents/Photos".

And my source code is just follows:

var imageSection: some View {
    Image(landmark.photoName,bundle: Bundle(url:FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!.appendingPathComponent("Photos")))
}

When running, it would get the error: [SwiftUI] No image named '0.jpg' found in asset catalog for /var/mobile/Containers/Data/Application/E03608D6-24A5-4797-8C16-DDAEB03AB623/Documents/Photos

And I am sure the jpg file is existing, because I use UIImage as parameter and it would display well:

var imageSection: some View {
    Image(uiImage: UIImage(named: "/var/mobile/Containers/Data/Application/EB3DA19A-F7B2-48DD-8681-139C7FCB9090/Documents/Photos/0.jpg"))
}

How could I display the image in the Image without UIImage?

Thank you very much!

Upvotes: 2

Views: 648

Answers (1)

Asperi
Asperi

Reputation: 258345

See documented Image constructor

/// Creates a labeled image usable as content for controls.
///
/// - Parameters:
///     - name: the name of the image resource to lookup, as well as
///       the localization key with which to label the image.
///     - bundle: the bundle to search for the image resource and
///       localization content. If `nil`, uses the main `Bundle`.
///       Defaults to `nil`.
public init(_ name: String, bundle: Bundle? = nil)

This one "name: the name of the image resource to lookup" - not a file name, but image resource name, and all image resources are now in assets catalogs.

For external images there is Image(uiImage:) which you already found - just use it.

Upvotes: 2

Related Questions