URL decode in objective-c [closed]

2019-09-20 04:34发布

问题:

i have a string named url i.e

NSString *url = @"http://sound17.mp3pk.com/indian/barfi/%5BSongs.PK%5D%20
              Barfi%20-%2001%20-%20Barfi!.mp3";

Now I am downloading this song and to save this I need to specify filename.I want the filename in such a way that It should take the file name itself from url.like in this url,It should take %5BSongs.PK%5D%20 Barfi%20-%2001%20-%20Barfi!.mp3 which is the file name in the url but should not be consist of Url formatters.

what I am doing is

Dest_path=[NSHomeDirectory() stringByAppendingString:@"/Documents/a3"];

result =[Dest_path stringByAppendingString:@".mp3"];
helper = [DownloadHelper download:url withTargetPath:result withDelegate:self];

回答1:

Something like this should work:

NSString *URLString = @"http://sound17.mp3pk.com/indian/barfi/%5BSongs.PK%5D%20Barfi%20-%2001%20-%20Barfi!.mp3";
NSURL *URL = [NSURL URLWithString:url];
NSString *filename = [[[URL path] lastPathComponent] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//=> [Songs.PK] Barfi - 01 - Barfi!.mp3

Note that you cannot always get a useful filename from just a URL, if the content is dynamic (e.g. something like http://example.com/getsong?q=foobar).

Edit: A better way to get a file name from an arbitrary URL would be to make a request and inspect the Content-Disposition HTTP header of the response.