How to get the filename from the filepath in swift
Solution 1:
Objective C
NSString* theFileName = [string lastPathComponent]
Swift
let theFileName = (string as NSString).lastPathComponent
Solution 2:
SWIFT 3.x or SWIFT 4:
Shortest and cleanest way of doing this is below. In this example url
variable is type of URL
in this way we can have a human readable String
result of the full file name with extension like My file name.txt
and Not like My%20file%20name.txt
// Result like: My file name.txt
let fileName = url.lastPathComponent
Solution 3:
If you want to get the current file name such as for logging purposes, I use this.
Swift 4
URL(fileURLWithPath: #file).lastPathComponent
Solution 4:
Swift 2:
var file_name = NSURL(fileURLWithPath: path_to_file).lastPathComponent!
Solution 5:
Try this
let filename: String = "your file name"
let pathExtention = filename.pathExtension
let pathPrefix = filename.stringByDeletingPathExtension
Updated :
extension String {
var fileURL: URL {
return URL(fileURLWithPath: self)
}
var pathExtension: String {
return fileURL.pathExtension
}
var lastPathComponent: String {
return fileURL.lastPathComponent
}
}
Hope it helps.