Reputation: 201
I am struggling with loading an image to Image. I am making an MacOS app which is slightly different than for iOS.
I searched Internet however I found only several responses how to make it in iOS.
Please check the code:
import SwiftUI
struct ContentView: View {
let myUrl = URL(fileURLWithPath: "/Users/codegrinder/Documents/turtlerock.jpg")
init() {
//TODO Do something with the myUrl which is valid (not nil)
}
var body: some View {
Image("turtlerock")
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment:.center)
//I need to put the param to Image what I want to load an image from myUrl
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
Upvotes: 5
Views: 2808
Reputation: 236260
First click on your app target > signing & capabilities and remove the App Sandbox as shown in the following picture:
Now you can access files that are not located inside your app bundle.
struct ContentView: View {
let image = NSImage(contentsOf: URL(fileURLWithPath: "/Users/codegrinder/Documents/turtlerock.jpg"))!
var body: some View {
Image(nsImage: image)
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment:.center)
}
}
Upvotes: 9