128

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

12 Answers 12

207

Objective C

NSString* theFileName = [string lastPathComponent]

Swift

let theFileName = (string as NSString).lastPathComponent
3
  • 2
    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
  • 3
    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
41

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
3
  • 3
    this always returns asset.JPG for images. Nov 25, 2016 at 10:16
  • 1
    See the Swift 2 answer which includes Swift 3 and is more coherent.
    – Tyler A.
    Feb 9, 2017 at 15:26
  • mine too - @HarshNigam
    – Dansp
    Mar 2, 2017 at 19:45
36

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

Swift 4

URL(fileURLWithPath: #file).lastPathComponent
1
  • 3
    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
25

Swift 2:

var file_name = NSURL(fileURLWithPath: path_to_file).lastPathComponent!
2
  • 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
22
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.

0
16

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.

0
11

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
6

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.

1
  • 1
    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
5

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.
1
  • 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
3

Swift 5. This one works faster than both URL and NSString options:

path.components(separatedBy: "/").last
1

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

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

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
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.