How to split filename from file extension in Swift?

前端 未结 21 1909
陌清茗
陌清茗 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<T: Encodable>(object: T, in fixturePath: String) throws {
            let data = try JSONEncoder().encode(object)
            try data.write(to: fixtureUrl(for: fixturePath))
        }
    
        func loadFixture<T: Decodable>(in fixturePath: String, as decodableType: T.Type) throws -> T {
            let data = try loadFixture(in: fixturePath)
            return try JSONDecoder().decode(decodableType, from: data)
        }
    
    }
    
    0 讨论(0)
  • 2020-12-01 04:12

    Creates unique "file name" form url including two previous folders

    func createFileNameFromURL (colorUrl: URL) -> String {
    
        var arrayFolders = colorUrl.pathComponents
    
        // -3 because last element from url is "file name" and 2 previous are folders on server
        let indx = arrayFolders.count - 3
        var fileName = ""
    
        switch indx{
        case 0...:
            fileName = arrayFolders[indx] + arrayFolders[indx+1] + arrayFolders[indx+2]
        case -1:
            fileName = arrayFolders[indx+1] + arrayFolders[indx+2]
        case -2:
            fileName = arrayFolders[indx+2]
        default:
            break
        }
    
    
        return fileName
    }
    
    0 讨论(0)
  • Swift 5 with code sugar

    extension String {
        var fileName: String {
           URL(fileURLWithPath: self).deletingPathExtension().lastPathComponent
        }
    
        var fileExtension: String{
           URL(fileURLWithPath: self).pathExtension
        }
    }
    
    0 讨论(0)
提交回复
热议问题