MacOS: How/where do I store a programmatically created file within my app folder?

自作多情 提交于 2021-01-02 03:55:12

问题


Very new to MacOS development (as in, completely new). I've developed a MacOS app (SwiftUI / Swift) and now figuring out a very things related to deployment.

My app generates a text file, but I'd like to save it within the app's folder (or whatever it is called) - and not in a user specified folder, and read it when I want. I can read resources from the Assets.xcassets but I'd like to be able to save as well without making the user choose a location.

Is there a way I can write/read from the app folder (I'm struggling to explain as I'm very unfamiliar with this system)?


回答1:


Yes you can create a directory inside your application support folder, name it with app’s bundle identifier or your company and store all files that are not accessible to the user there:

Use this directory to store all app data files except those associated with the user’s documents. For example, you might use this directory to store app-created data files, configuration files, templates, or other fixed or modifiable resources that are managed by the app. An app might use this directory to store a modifiable copy of resources contained initially in the app’s bundle. A game might use this directory to store new levels purchased by the user and downloaded from a server. All content in this directory should be placed in a custom subdirectory whose name is that of your app’s bundle identifier or your company.

You should take some time and read the File System Basics documentation

do {
    let applicationSupport = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first!
    let bundleID = Bundle.main.bundleIdentifier ?? "company name"
    let appSupportSubDirectory = applicationSupport.appendingPathComponent(bundleID,isDirectory: true)
    try FileManager.default.createDirectory(at: appSupportSubDirectory, withIntermediateDirectories: true, attributes: nil)
    print(appSupportSubDirectory.path) // /Users/.../Library/Application Support/YourBundleIdentifier
} catch {
    print(error)
}


来源:https://stackoverflow.com/questions/62207403/macos-how-where-do-i-store-a-programmatically-created-file-within-my-app-folder

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