问题
I am trying to read .json
file in my unit test and running it within Swift Package. Using Xcode 11 and Swift 5.1
let path = Bundle.main.url(forResource: filename, withExtension: "json")
// Path is nil
I've been told that Swift packages don't have bundles any more. So how can I workaround this?
Part of my Swift.package
.testTarget(
name: "ProjectTests",
dependencies: [
.target(name: "Project")
],
path: "Tests",
exclude: [
"Folder/File.swift"
]
)
回答1:
The solution we have found is FileManager
.
var cache: [String: URL] = [:] // Save all local files in this cache
let baseURL = urlForRestServicesTestsDir()
guard let enumerator = FileManager.default.enumerator(
at: baseURL,
includingPropertiesForKeys: [.nameKey],
options: [.skipsHiddenFiles, .skipsPackageDescendants],
errorHandler: nil) else {
fatalError("Could not enumerate \(baseURL)")
}
for case let url as URL in enumerator where url.isFileURL {
cache[url.lastPathComponent] = url
}
You will need this method
static func urlForRestServicesTestsDir() -> URL {
let currentFileURL = URL(fileURLWithPath: "\(#file)", isDirectory: false)
return currentFileURL
.deletingLastPathComponent()
.deletingLastPathComponent()
}
After this you can get URL for every file:
func url(for fileName: String) -> URL? {
return cache[fileName]
}
In case you will only want to run this code in Swift package use #if SWIFT_PACKAGE
.
来源:https://stackoverflow.com/questions/57555856/get-url-to-a-local-file-with-spm-swift-package-manager