从NSURL中检索文件名

far*_*usa 29 nsurl

我有一个URL

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

我想提取文件名"honda_v4_concept_widescreen_bike-wide.jpg"

我怎么能这样做?

Apo*_*ARE 50

下面的代码应该有效.更新了它,所以我删除了顶部声明.我可以使用NSString vs const char*或来自C++的std :: string,但我认为C Character Pointers非常适合这种情况.

还改进了它,因此它有自己的简洁功能:

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

使用:

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_]);
Run Code Online (Sandbox Code Playgroud)

  • 我强烈建议**反对**这里的第一个代码片段.第二个很好 (4认同)
  • `NSURL.lastPathComponent`甚至适用于`fileReferenceURL`风格的URL.使用`absoluteString`代替将导致"id = 65134 ......" (3认同)
  • 1.假装URL是一条路径; 他们不是.如果URL碰巧在路径之后有任何组件(即参数,片段或查询),那将搞砸这个例程 (2认同)