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

折月煮酒 提交于 2020-12-21 03:53:44

问题


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

回答1:


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


来源:https://stackoverflow.com/questions/64561842/how-to-load-an-image-from-documents-directory-on-macos-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!