Get URL to a local file with SPM (Swift Package Manager)

蓝咒 提交于 2020-01-11 06:55:08

问题


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

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