24

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!

2
  • 1
    Try stringByRemovingPercentEncoding. Jan 3, 2014 at 17:52
  • 1
    Further to the accepted answer, this is quite a fragile way to arrive at your S%C3%A1ndor_Font string in the first place. I suspect -[NSURL lastPathComponent] is what you're after Jan 9, 2014 at 19:27

4 Answers 4

44

For iOS10/Swift 3:

substring.removingPercentEncoding

For iOS9/Swift 2.3:

substring.stringByRemovingPercentEncoding

2
41

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

I.e.

[substring stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
3
  • Awesome! Worked perfectly and I will accept your answer as soon as it lets me! Thanks! Jan 3, 2014 at 17:56
  • 2
    'stringByReplacingPercentEscapesUsingEncoding:' is deprecated:first deprecated in macOS 10.11 - Use -stringByRemovingPercentEncoding instead, which always uses the recommended UTF-8 encoding.
    – Chrstpsln
    Apr 12, 2017 at 6:54
  • Is there a reasonably decent way to accomplish this prior to 10.9? I guess then I just need to test the OS version or catch an exception and call stringByReplacingPercentEscapesUsingEncoding?
    – Tom Bogle
    Nov 1, 2017 at 1:31
16

Swift 3

str.removingPercentEncoding
1
  • 1
    sweet answer! :)
    – Fattie
    May 6, 2017 at 21:33
7

Swift 4.2 (Linux support)

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.