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
To extract filename from the file, we use “GetFileName()” method of “Path” class. This method is used to get the file name and extension of the specified path string. The returned value is null if the file path is null. Syntax: public static string GetFileName (string path);
Objective C
NSString* theFileName = [string lastPathComponent]
Swift
let theFileName = (string as NSString).lastPathComponent
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With