Retrieve filename from NSURL

farisolusa picture farisolusa · Nov 13, 2013 · Viewed 16.1k times · Source

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?

Answer

Apollo SOFTWARE picture Apollo SOFTWARE · Nov 13, 2013

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