【发布时间】:2023-03-20 05:55:01
【问题描述】:
我刚刚找到了如何在 macOS 下确定文档文件夹。 但我喜欢找到我的二进制文件所在的文件夹。 我想加载一个文件,该文件与我的二进制文件存储在同一目录中。
【问题讨论】:
-
使用
NSBundle.mainBundle().pathForResource
我刚刚找到了如何在 macOS 下确定文档文件夹。 但我喜欢找到我的二进制文件所在的文件夹。 我想加载一个文件,该文件与我的二进制文件存储在同一目录中。
【问题讨论】:
NSBundle.mainBundle().pathForResource
2020 | SWIFT 5.1:
let appFolder = Bundle.main.resourceURL
【讨论】:
使用以下代码查找应用程序目录:
let dirPaths = NSSearchPathForDirectoriesInDomains(.ApplicationDirectory,
.UserDomainMask, true)
NSLog("%@", dirPaths.first!);
要查找二进制文件所在的目录,可以很容易地识别为(@vadian 已经建议):
NSBundle.mainBundle().bundleURL.URLByDeletingLastPathComponent!
【讨论】:
let path = NSBundle.mainBundle().bundleURL.URLByDeletingLastPathComponent!.URLByAppendingPathComponent(file)
我认为NSBundle.mainBundle() 是您正在寻找的。您可以使用NSBundle.mainBundle().pathForResource("file", ofType: "txt") 来加载文件
【讨论】:
这对我有用(使用 iOS):
let directoryPaths = NSSearchPathForDirectoriesInDomains(.applicationDirectory, .userDomainMask, true)
if let firstURL = directoryPaths.first, let url = URL(string: firstURL)?.deletingLastPathComponent() {
print("App files url: \(url.path)")
}
【讨论】:
斯威夫特 5:
var appURL = URL(fileURLWithPath: Bundle.main.bundleURL.absoluteString)
// Remove app from URL to get directory path
appURL.deleteLastPathComponent()
【讨论】: