How to get the filename from the filepath in swift

IosIphoneSwift

Ios Problem Overview


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

Ios Solutions


Solution 1 - Ios

Objective C

NSString* theFileName = [string lastPathComponent]

Swift

let theFileName = (string as NSString).lastPathComponent

Solution 2 - Ios

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 - Ios

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 - Ios

Swift 2:

var file_name = NSURL(fileURLWithPath: path_to_file).lastPathComponent!

Solution 5 - Ios

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.

Solution 6 - Ios

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.

Solution 7 - Ios

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

Solution 8 - Ios

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.

Solution 9 - Ios

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

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

Solution 10 - Ios

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.

Solution 11 - Ios

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

}

Solution 12 - Ios

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

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRalphView Question on Stackoverflow
Solution 1 - IosSujith ChandranView Answer on Stackoverflow
Solution 2 - IosTrevorView Answer on Stackoverflow
Solution 3 - IosHedyloveView Answer on Stackoverflow
Solution 4 - IosVingtoftView Answer on Stackoverflow
Solution 5 - IosRobacView Answer on Stackoverflow
Solution 6 - IosPradumna PatilView Answer on Stackoverflow
Solution 7 - IosAshuView Answer on Stackoverflow
Solution 8 - IosNishant SharmaView Answer on Stackoverflow
Solution 9 - IosAnton PlebanovichView Answer on Stackoverflow
Solution 10 - IosDnVView Answer on Stackoverflow
Solution 11 - IosPvlubView Answer on Stackoverflow
Solution 12 - IosTaiwosamView Answer on Stackoverflow