Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
276 views
in Technique[技术] by (71.8m points)

How to load an image from documents directory on macOS Swift?

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()
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

First click on your app target > signing & capabilities and remove the App Sandbox as shown in the following picture:

enter image description here

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)
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...