使用SPM(Swift Package Manager)获取指向本地文件的URL

时间:2019-08-19 11:30:08

标签: swift swift-package-manager

我正在尝试在单元测试中读取.json文件,并在Swift Package中运行它。使用Xcode 11和Swift 5.1

let path = Bundle.main.url(forResource: filename, withExtension: "json")
// Path is nil

有人告诉我Swift软件包不再包含捆绑软件。那么我该如何解决呢?

我的Swift.package的一部分

.testTarget(
    name: "ProjectTests", 
    dependencies: [
        .target(name: "Project")
    ],
    path: "Tests",
    exclude: [
        "Folder/File.swift"
    ]
)

1 个答案:

答案 0 :(得分:0)

我们找到的解决方案是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
}

您将需要此方法

static func urlForRestServicesTestsDir() -> URL {
    let currentFileURL = URL(fileURLWithPath: "\(#file)", isDirectory: false)
    return currentFileURL
        .deletingLastPathComponent()
        .deletingLastPathComponent()
}

此后,您可以获得每个文件的URL:

func url(for fileName: String) -> URL? {
    return cache[fileName]
}

如果您只想在Swift软件包中运行此代码,请使用#if SWIFT_PACKAGE