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

前端 未结 1 721
北荒
北荒 2021-01-06 05:32

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         


        
相关标签:
1条回答
  • 2021-01-06 05:47

    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.

    0 讨论(0)
提交回复
热议问题