function to get the file name of an URL

前端 未结 6 1828
时光说笑
时光说笑 2021-01-30 05:23

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

相关标签:
6条回答
  • 2021-01-30 05:33

    Try this:

    Edit: from blow comment

    NSString *url = @"http://www.google.com/a.pdf";
    NSArray *parts = [url componentsSeparatedByString:@"/"];
    NSString *filename = [parts lastObject];
    
    0 讨论(0)
  • 2021-01-30 05:36

    Swift 3

    Let's say that your url is http://www.google.com/a.pdf

        let filename = url.lastPathComponent
    
        \\filename = "a.pdf"
    
    0 讨论(0)
  • 2021-01-30 05:39

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

    0 讨论(0)
  • 2021-01-30 05:40

    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];
    
    0 讨论(0)
  • 2021-01-30 05:47

    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];
    
    0 讨论(0)
  • 2021-01-30 05:48

    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];
    
    0 讨论(0)
提交回复
热议问题