ios 如何删除/解码 URL 百分比编码?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20909683/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I remove/decode URL percent encoding?
提问by user2844801
I want to take a url
and convert it to a more readableformat. For example I have the following link:
我想将 aurl
转换为更易读的格式。例如我有以下链接:
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?
我带走了不必要的部分,并"S%C3%A1ndor_Font"
作为NSString
. 有什么方法可以将其转换为"Sándor Font"
(它实际上应该是什么),而不必输入特殊字符的每个组合并替换字符串的每个部分?
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!
最后,我希望标签说"Sándor Font"
没有"S%C3%A1ndor_Font"
。谢谢!
回答by Josh The Geek
- (NSString *)stringByReplacingPercentEscapesUsingEncoding:(NSStringEncoding)encoding;
on NSString is what you want.
- (NSString *)stringByReplacingPercentEscapesUsingEncoding:(NSStringEncoding)encoding;
在 NSString 上是你想要的。
I.e.
IE
[substring stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
回答by Frankie
For iOS10/Swift 3:
对于 iOS10/Swift 3:
substring.removingPercentEncoding
substring.removingPercentEncoding
For iOS9/Swift 2.3:
对于 iOS9/Swift 2.3:
substring.stringByRemovingPercentEncoding
substring.stringByRemovingPercentEncoding
回答by quemeful
Swift 3
斯威夫特 3
str.removingPercentEncoding
回答by Sergey Di
Swift 4.2 (Linux support)
Swift 4.2(Linux 支持)
let percentString = "hello%20world"
let string = NSString(string: percentString).removingPercentEncoding!
print(string) // hello world