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(forR
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
.