How to split filename from file extension in Swift?

前端 未结 21 1954
陌清茗
陌清茗 2020-12-01 03:24

Given the name of a file in the bundle, I want load the file into my Swift app. So I need to use this method:

let soundURL = NSBundle.mainBundle().URLForReso         


        
21条回答
  •  误落风尘
    2020-12-01 04:10

    Maybe I'm getting too late for this but a solution that worked for me and consider quite simple is using the #file compiler directive. Here is an example where I have a class FixtureManager, defined in FixtureManager.swift inside the /Tests/MyProjectTests/Fixturesdirectory. This works both in Xcode and withswift test`

    import Foundation
    
    final class FixtureManager {
    
        static let fixturesDirectory = URL(fileURLWithPath: #file).deletingLastPathComponent()
    
        func loadFixture(in fixturePath: String) throws -> Data {
            return try Data(contentsOf: fixtureUrl(for: fixturePath))
        }
    
        func fixtureUrl(for fixturePath: String) -> URL {
            return FixtureManager.fixturesDirectory.appendingPathComponent(fixturePath)
        }
    
        func save(object: T, in fixturePath: String) throws {
            let data = try JSONEncoder().encode(object)
            try data.write(to: fixtureUrl(for: fixturePath))
        }
    
        func loadFixture(in fixturePath: String, as decodableType: T.Type) throws -> T {
            let data = try loadFixture(in: fixturePath)
            return try JSONDecoder().decode(decodableType, from: data)
        }
    
    }
    

提交回复
热议问题