Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I remove/decode URL percent encoding?

Tags:

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!

like image 419
user2844801 Avatar asked Jan 03 '14 17:01

user2844801


People also ask

How do I stop URL encoding?

Another interesting oddity is that when you copy URLs out of Firefox or Chrome they are URL encoded, which can be very annoying. To prevent this simply type a character in the URL and erase it, before you copy the URL.

Does browsers automatically decode URL?

kinda de-facto standard yes. but only in modern browsers. its done for user convienience, so you can put utf8 charactesr in an url and its still pretty to the human eye. however please be aware that the text is actually still encoded and will be transmittet/requested encoded, it is only displayed decoded.

How do you change the special characters in a URL?

URL encoding replaces unsafe ASCII characters with a "%" followed by two hexadecimal digits. URLs cannot contain spaces. URL encoding normally replaces a space with a plus (+) sign or with %20.

Why is %20 used in URLs?

A space is assigned number 32, which is 20 in hexadecimal. When you see “%20,” it represents a space in an encoded URL, for example, http://www.example.com/products%20and%20services.html.


1 Answers

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

I.e.

[substring stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
like image 144
Josh The Geek Avatar answered Oct 14 '22 07:10

Josh The Geek