Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS : How to do proper URL encoding?

People also ask

What is the best way to URL encode a string?

The recommended encoding scheme to use is UTF-8.

What does %20 in a URL mean?

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.

How do you encode a URL?

Since URLs often contain characters outside the ASCII set, the URL has to be converted into a valid ASCII format. 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.

What is addingPercentEncoding?

addingPercentEncoding(withAllowedCharacters:) Returns a new string made from the receiver by replacing all characters not in the specified set with percent-encoded characters.


The answer @Dhaval Vaishnani provided is only partially correct. This method treats the ?, = and & characters as not to be encoded, since they're valid in an URL. Thus, to encode an arbitrary string to be safely used as a part of an URL, you can't use this method. Instead you have to fall back to using CoreFoundation and CFURLRef:

NSString *unsafeString = @"this &string= confuses ? the InTeRwEbZ";
CFStringRef safeString = CFURLCreateStringByAddingPercentEscapes (
    NULL,
    (CFStringRef)unsafeString,
    NULL,
    CFSTR("/%&=?$#+-~@<>|\\*,.()[]{}^!"),
    kCFStringEncodingUTF8
);

Don't forget to dispose of the ownership of the resulting string using CFRelease(safeString);.

Also, it seems that despite the title, OP is looking for decoding and not encoding a string. CFURLRef has another, similar function call to be used for that:

NSString *escapedString = @"%32%65BCDEFGH";
CFStringRef unescapedString = CFURLCreateStringByReplacingPercentEscapesUsingEncoding (
    NULL,
    (CFStringRef)escapedString,
    CFSTR(""),
    kCFStringEncodingUTF8
);

Again, don't forget proper memory management.


I did some tests and I think the problem is not really with the UIWebView but instead that NSURL won't accept the URL because of the é in "Témp" is not encoded properly. This will cause +[NSURLRequest requestWithURL:] and -[NSURL URLWithString:] to return nil as the string contains a malformed URL. I guess that you then end up using a nil request with -[UIViewWeb loadRequest:] which is no good.

Example:

NSLog(@"URL with é: %@", [NSURL URLWithString:@"http://host/Témp"]);
NSLog(@"URL with encoded é: %@", [NSURL URLWithString:@"http://host/T%C3%A9mp"]);

Output:

2012-10-02 12:02:56.366 test[73164:c07] URL with é: (null)
2012-10-02 12:02:56.368 test[73164:c07] URL with encoded é: http://host/T%C3%A9mp

If you really really want to borrow the graceful handling of malformed URLs that WebKit has and don't want to implement it yourself you can do something like this but it is very ugly:

UIWebView *webView = [[[UIWebView alloc]
                       initWithFrame:self.view.frame]
                      autorelease];

NSString *url = @"http://www.httpdump.com/texis/browserinfo/Témp.html";

[webView loadHTMLString:[NSString stringWithFormat:
                         @"<script>window.location=%@;</script>",
                         [[[NSString alloc]
                           initWithData:[NSJSONSerialization
                                         dataWithJSONObject:url
                                         options:NSJSONReadingAllowFragments
                                         error:NULL]
                           encoding:NSUTF8StringEncoding]
                          autorelease]]
                baseURL:nil];

The most straightforward way is to use:

NSString *encodedString = [rawString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

iDhaval was close, but he was doing it the other way around (decoding instead of encoding).

Anand's way would work, but you'll most likely have to replace more characters than spaces and new lines. See the reference here: http://en.wikipedia.org/wiki/Percent-encoding#Percent-encoding_reserved_characters

Hope that helps.


It's very simple to encode the URL in iPhone. It is as following

NSString* strURL = @"http://somedomain.com/data/Témp Page - Open.html";

NSURL* url = [NSURL URLWithString:[strURL stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];

It's a perfect way to encode the URL, I am using it and it's perfectly work with me.

Hope it will help you!!!