In my SwiftUI app I have a view for people to edit a book's metadata, such as its title and author. In this view I have an image view that shows the book's cover image.
struct ImageView: View {
@Binding var book: Book
var body: some View {
// coverImage is the URL to the image file.
let image = NSImage(byReferencing:
book.metadata.coverFile)
Image(nsImage: image)
.aspectRatio(contentMode: .fit)
}
}
When I open a book that I've set a cover image and open the metadata editor, the image view displays nothing. The metadata editor has a button to choose a cover image. When I click the button and choose an image file from the file importer, the image appears in the image view. If I close the book, reopen it, and open the metadata editor, the image appears in the image view. But if I restart the app, open the book, and open the metadata editor, the image view displays nothing.
I have tried the various NSImage
initializers. I tried building the image from a Data
object and from NSBitmapImageRep
. But when I set a breakpoint in the image view and check the image
variable, it's either nil or invalid. When I check the coverfile
variable, it displays the proper URL, including the .png
extension.
In an AppKit version of this app, I have the same code to create the NSImage
, and the image displays in the image view.
How do I get an existing image file to display in the image view without clicking the Choose Cover button and choosing the file again from the file importer?