How to split filename from file extension in Swift?

前端 未结 21 1910
陌清茗
陌清茗 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:01

    In Swift 2.1 String.pathExtension is not available anymore. Instead you need to determine it through NSURL conversion:

    NSURL(fileURLWithPath: filePath).pathExtension
    
    0 讨论(0)
  • 2020-12-01 04:02

    Works in Swift 5. Adding these behaviors to String class:

    extension String {
    
        func fileName() -> String {
            return URL(fileURLWithPath: self).deletingPathExtension().lastPathComponent 
        }
    
        func fileExtension() -> String {
            return URL(fileURLWithPath: self).pathExtension
        }
    }
    

    Example:

    let file = "image.png"
    let fileNameWithoutExtension = file.fileName()
    let fileExtension = file.fileExtension()
    
    0 讨论(0)
  • 2020-12-01 04:07

    Swift 3.0

     let sourcePath = NSURL(string: fnName)?.pathExtension
     let pathPrefix = fnName.replacingOccurrences(of: "." + sourcePath!, with: "")
    
    0 讨论(0)
  • 2020-12-01 04:09

    This is with Swift 2, Xcode 7: If you have the filename with the extension already on it, then you can pass the full filename in as the first parameter and a blank string as the second parameter:

    let soundURL = NSBundle.mainBundle()
        .URLForResource("soundfile.ext", withExtension: "")
    

    Alternatively nil as the extension parameter also works.

    If you have a URL, and you want to get the name of the file itself for some reason, then you can do this:

    soundURL.URLByDeletingPathExtension?.lastPathComponent
    

    Swift 4

    let soundURL = NSBundle.mainBundle().URLForResource("soundfile.ext", withExtension: "")
    soundURL.deletingPathExtension().lastPathComponent
    
    0 讨论(0)
  • 2020-12-01 04:09

    A cleaned up answer for Swift 4 with an extension off of PHAsset:

    import Photos
    
    extension PHAsset {
        var originalFilename: String? {
            if #available(iOS 9.0, *),
                let resource = PHAssetResource.assetResources(for: self).first {
                return resource.originalFilename
            }
    
            return value(forKey: "filename") as? String
        }
    }
    

    As noted in XCode, the originalFilename is the name of the asset at the time it was created or imported.

    0 讨论(0)
  • Swift 5.0 update:

    As pointed out in the comment, you can use this.

    let filename: NSString = "bottom_bar.png"
    let pathExtention = filename.pathExtension
    let pathPrefix = filename.deletingLastPathComponent
    
    0 讨论(0)
提交回复
热议问题