Retrieve filename from NSURL

不羁岁月 提交于 2019-12-05 08:45:15

问题


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?


回答1:


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



回答2:


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!")
}



回答3:


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



回答4:


simply use basename basename() function

$url = http://www.fullhdwallpapers.in/wp-content/uploads/2017/01/Logan-Movie-Kid-2017-680x425.jpg

echo basename($url); 


来源:https://stackoverflow.com/questions/19964198/retrieve-filename-from-nsurl

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!