Reputation: 1
I have a PNG file in my Bundle.main and I want use that URL or path to feed my Image in SwiftUI, right now I am using this down code, but I like to use just SwiftUI not UIKit mixed
Image(uiImage: UIImage(contentsOfFile: path)!)
Do we have some initializing way for Image that accept path or url?
Upvotes: 1
Views: 1318
Reputation: 28539
If you want to init from a filepath you could create an extension on Image that handles the boilerplate code for you. But you need to handle the case if the UIImage doesn't exist as the Image(uiImage:)
expects a non-optional UIImage as a parameter.
Something like this should work:
extension Image {
init(contentsOfFile: String) {
// You could force unwrap here if you are 100% sure the image exists
// but it is better to handle it gracefully
if let image = UIImage(contentsOfFile: contentsOfFile) {
self.init(uiImage: image)
} else {
// You need to handle the option if the image doesn't exist at the file path
// let's just initialize with a SF Symbol as that will exist
// you could pass a default name or otherwise if you like
self.init(systemName: "xmark.octagon")
}
}
}
You would then use it like this:
Image(contentsOfFile: "path/to/image/here")
Or you could use the property of UIImage
to load from the bundle
extension Image {
init(uiImageNamed: String) {
if let image = UIImage(named: uiImageNamed, in: .main, compatibleWith: nil) {
self.init(uiImage: image)
} else {
// You need to handle the option if the image doesn't exist at the file path
self.init(systemName: "xmark.octagon")
}
}
}
You would then use it like this:
Image(uiImageNamed: "ImageName")
Upvotes: 2