如何删除/解码URL百分比编码?

时间:2014-01-03 17:48:04

标签: ios objective-c nsstring nsurlconnection nsurl

我想采用url并将其转换为更强大的可读格式。例如,我有以下链接:

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

我带走了不必要的部分,并留下"S%C3%A1ndor_Font"作为NSString。有没有什么方法可以将它转换为"Sándor Font"(实际应该是什么),而不必输入特殊字符的每一个组合并替换字符串的每个部分?

为了演示我想如何使用它,我编写了以下示例代码:

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

最后,我希望标签说"Sándor Font"而不是"S%C3%A1ndor_Font"。谢谢!

4 个答案:

答案 0 :(得分:37)

NSString上的

- (NSString *)stringByReplacingPercentEscapesUsingEncoding:(NSStringEncoding)encoding;就是你想要的。

[substring stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

答案 1 :(得分:33)

对于iOS10 / Swift 3:

substring.removingPercentEncoding

对于iOS9 / Swift 2.3:

substring.stringByRemovingPercentEncoding

答案 2 :(得分:10)

Swift 3

str.removingPercentEncoding

答案 3 :(得分:3)

Swift 4.2(Linux支持)

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