How do I remove/decode URL percent encoding?

user2844801 picture user2844801 · Jan 3, 2014 · Viewed 30.8k times · Source

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!

Answer

Josh The Geek picture Josh The Geek · Jan 3, 2014

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

I.e.

[substring stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];