I have some source code to get the file name of an url
for example:
http://www.google.com/a.pdf
I hope to get a.pdf
because the way to join 2 NSS
Try this:
Edit: from blow comment
NSString *url = @"http://www.google.com/a.pdf";
NSArray *parts = [url componentsSeparatedByString:@"/"];
NSString *filename = [parts lastObject];
Swift 3
Let's say that your url is http://www.google.com/a.pdf
let filename = url.lastPathComponent
\\filename = "a.pdf"
I haven't tried this yet, but it seems like you might be trying to do this the hard way. The iPhone libraries have the NSURL
class, and I imagine that you could simply do:
NSString *url = [NSURL URLWithString:@"http://www.google.com/a.pdf"];
NSString *path = [url path];
Definitely look for a built in function. The libraries have far more testing and will handle the edge cases better than anything you or I will write in an hour or two (generally speaking).
I think if you have already had the NSURL
object, there is lastPathComponent
method available from the iOS 4 onwards.
NSURL *url = [NSURL URLWithString:@"http://www.google.com/a.pdf"];
NSString *filename = [url lastPathComponent];
This is more error free and meant for getting the localized name in the URL.
NSString *localizedName = nil;
[url getResourceValue:&localizedName forKey:NSURLLocalizedNameKey error:NULL];
The following line does the job if url is a NSString:
NSString *filename = [url lastPathComponent];
If url is a NSURL, then the following does the job:
NSString *filename = [[url path] lastPathComponent];