Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

How to get the filename from the given file path string?

For example if I have a filepath string as

file:///Users/DeveloperTeam/Library/Developer/CoreSimulator/Devices/F33222DF-D8F0-448B-A127-C5B03C64D0DC/data/Containers/Data/Application/5D0A6264-6007-4E69-A63B-D77868EA1807/tmp/trim.D152E6EA-D19D-4E3F-8110-6EACB2833CE3.MOV

and I would like to get the return result as

trim.D152E6EA-D19D-4E3F-8110-6EACB2833CE3.MOV
                maybe you should highlight in Swift that this works only for NSString, like:  var theFileName: NSString = string.lastPathComponent // or var theFileName: String = (string as NSString).lastPathComponent
– Babac
                Mar 23, 2016 at 10:16
                in Swift, local filenames are highly suggested to be managed as URLs, not as Strings or NSStrings
– bshirley
                Sep 22, 2018 at 16:01
                Note that this requires Foundation to be imported. Not a big deal for iOS/Mac apps, but a big deal for Linux/Windows ones.
– Cristik
                Sep 16, 2021 at 16:11

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

If you want to get the current file name such as for logging purposes, I use this.

Swift 4

URL(fileURLWithPath: #file).lastPathComponent
                Good to know: use init(fileURLWithPath path: __shared String, isDirectory: Bool) to avoid an extra file system access. From the docs: This function avoids an extra file system access to check if the file URL is a directory. You should use it if you know the answer already.
– Mark
                Sep 3, 2019 at 10:39
                This is the method the compiler says to use if you call lastPathComponent on a swift String (as opposed to casting to NSString).
– i_am_jorf
                Oct 12, 2016 at 22:15
                Good to know: use init(fileURLWithPath path: __shared String, isDirectory: Bool) to avoid an extra file system access. From the docs: This function avoids an extra file system access to check if the file URL is a directory. You should use it if you know the answer already.
– Mark
                Sep 3, 2019 at 10:39
let theURL = URL(string: "yourURL/somePDF.pdf")  //use your URL
let fileNameWithExt = theURL?.lastPathComponent //somePDF.pdf
let fileNameLessExt = theURL?.deletingPathExtension().lastPathComponent //somePDF

In order for this to work your url must be of type URL not a string so don't convert it to a string before hand.

You can copy and paste this code directly into playground to see how it works.

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.

Below code is working for me in Swift 4.X

 let filename = (self.pdfURL as NSString).lastPathComponent  // pdfURL is your file url
 let fileExtention = (filename as NSString).pathExtension  // get your file extension
 let pathPrefix = (filename as NSString).deletingPathExtension   // File name without extension
 self.lblFileName.text = pathPrefix  // Print name on Label

You can pass the url in fileUrl, like I did below:-

let fileUrl: String = "https://www.himgs.com/imagenes/hello/social/hello-fb-logo.png" // Pass the URL 
let lastPathComponent = URL.init(string: fileUrl)?.lastPathComponent ?? "" // With this you will get last path component
let fileNameWithExtension = lastPathComponent

//This last path component will provide you file Name with extension.

This is a little-appreciated code-only answer. Please add some explanation. That will improve your chances for upvotes and also helps fighting the misconception that you can get programming work done here free of charge. – Yunnosch Sep 11, 2019 at 6:32

I've done some performance tests (iOS 14, real device, release configuration):

(#file as NSString).lastPathComponent // The fastest option.
URL(string: #file)!.lastPathComponent // 2.5 times slower than NSString.
#file.components(separatedBy: "/").last! // 7 times slower than NSString.

Bonus:

URL(fileURLWithPath: #file, isDirectory: false).lastPathComponent // About the same as URL(string:).
URL(fileURLWithPath: #file).lastPathComponent // 2.5 times slower than with explicit isDirectory.
                While (#file as NSString) is the fastest, you'll get escaped stuff like %20 in the result, which is resolved in the URL(string: #file) case.
– Lerk
                Nov 19, 2022 at 23:46

To retrieve filename without its extension from a URL in Swift >= 4.2:

let urlWithoutFileExtension: URL =  originalFileUrl.deletingPathExtension()
let fileNameWithoutExtension: String = urlWithoutFileExtension.lastPathComponent

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
        

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.