Ralph
Ralph

Reputation: 2095

How to get the filename from the filepath in swift

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

Upvotes: 128

Views: 123486

Answers (12)

Pvlub
Pvlub

Reputation: 11

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
}

Upvotes: 1

DnV
DnV

Reputation: 185

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.

Upvotes: 6

Anton Plebanovich
Anton Plebanovich

Reputation: 1516

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

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

Upvotes: 6

Robac
Robac

Reputation: 425

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.

Upvotes: 22

Nishant Sharma
Nishant Sharma

Reputation: 209

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.

Upvotes: 6

Ashu
Ashu

Reputation: 3523

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

Upvotes: 11

Taiwosam
Taiwosam

Reputation: 549

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

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

Upvotes: 1

Pradumna Patil
Pradumna Patil

Reputation: 2220

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.

Upvotes: 16

Jozey
Jozey

Reputation: 1740

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

Swift 4

URL(fileURLWithPath: #file).lastPathComponent

Upvotes: 36

Trevor
Trevor

Reputation: 1059

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

Upvotes: 42

Sujith Chandran
Sujith Chandran

Reputation: 2721

Objective C

NSString* theFileName = [string lastPathComponent]

Swift

let theFileName = (string as NSString).lastPathComponent

Upvotes: 210

Vingtoft
Vingtoft

Reputation: 14586

Swift 2:

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

Upvotes: 25

Related Questions