Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieve filename from NSURL

Tags:

nsurl

I have a URL

http://www.hdwallpapers.in/walls/honda_v4_concept_widescreen_bike-wide.jpg

I want to extract the file name which is "honda_v4_concept_widescreen_bike-wide.jpg"

How can I can do this?

like image 929
farisolusa Avatar asked Nov 13 '13 20:11

farisolusa


3 Answers

The code below should work. Updated it so I removed the top statement. I could've used NSString vs const char * or std::string from C++ but thought C Character Pointers would be quite appropriate for this case in point.

Also revamped this so it's in it's own concise function:

-(NSString*) extractFile:(const char*) url 
{
    NSURL *yourURL = [NSURL URLWithString:
                     [NSString stringWithCString:url 
                                 encoding:NSUTF8StringEncoding]];
    return [yourURL lastPathComponent];
}

to use:

const char *path_ = "http://www.hdwallpapers.in/walls/honda_v4_concept_widescreen_bike-wide.jpg";
NSLog(@"\t\tYour Extracted file: \n\t%@", [self extractFile:path_]);
like image 146
apollosoftware.org Avatar answered Nov 10 '22 05:11

apollosoftware.org


Swift 3:

let urlString = "http://www.hdwallpapers.in/walls/honda_v4_concept_widescreen_bike-wide.jpg"
if let url = URL(string: urlString) {
  print("file name: \(url.lastPathComponent)")
} else {
  print("error - not a valid url!")
}
like image 26
budiDino Avatar answered Nov 10 '22 03:11

budiDino


The code below works. absoluteString is recommended in another answer, but it doesn't work correctly if there are (e.g.) spaces in the filename.

NSString *JPEGfilename = [[yourURL path] lastPathComponent];
like image 1
Nestor Avatar answered Nov 10 '22 03:11

Nestor