Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the filename from the filepath in swift

Tags:

ios

swift

iphone

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 
like image 415
Ralph Avatar asked Aug 03 '15 06:08

Ralph


People also ask

How do I get filename and path?

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);


2 Answers

Objective C

NSString* theFileName = [string lastPathComponent] 

Swift

let theFileName = (string as NSString).lastPathComponent 
like image 68
Sujith Chandran Avatar answered Sep 28 '22 00:09

Sujith Chandran


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 
like image 36
Trevor Avatar answered Sep 28 '22 02:09

Trevor