How do I remove/decode URL percent encoding?

不问归期 提交于 2021-02-04 14:28:06

问题


I want to take a url and convert it to a more readable format. For example I have the following link:

http://en.wikipedia.org/wiki/S%C3%A1ndor_Font

I take away the unnecessary parts and am left with "S%C3%A1ndor_Font" as a NSString. Is there any sort of way to convert this into "Sándor Font" (what it actually should be), without having to type out every single combination of special characters and replacing each part of the string?

To demonstrate how I want to use this, I wrote the following sample code:

   //request is a NSURLRequest with a url of http://en.wikipedia.org/wiki/S%C3%A1ndor_Font

    NSRange range = [[request.URL absoluteString] rangeOfString:@"/wiki/"];

    NSString *substring = [[[request.URL absoluteString] substringFromIndex:NSMaxRange(range)] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];

    //ArticleTitleLabel is a UILabel

    self.ArticleTitleLabel.text = substring;

In the end I want the label to say "Sándor Font" not "S%C3%A1ndor_Font". Thanks!


回答1:


- (NSString *)stringByReplacingPercentEscapesUsingEncoding:(NSStringEncoding)encoding; on NSString is what you want.

I.e.

[substring stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];



回答2:


For iOS10/Swift 3:

substring.removingPercentEncoding

For iOS9/Swift 2.3:

substring.stringByRemovingPercentEncoding




回答3:


Swift 3

str.removingPercentEncoding



回答4:


Swift 4.2 (Linux support)

let percentString = "hello%20world"
let string = NSString(string: percentString).removingPercentEncoding!
print(string) // hello world


来源:https://stackoverflow.com/questions/20909683/how-do-i-remove-decode-url-percent-encoding

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