iOS : How to do proper URL encoding?

I'm unable to open a URL into UIWevView so I've seached & found that I need to encode URL, so I tried to encode it but, I've facing problem in URL encoding : My URL isémp%20Page%20-%20Open.html (It's not real URL).

I'm concerned with %20 that I tried to replace using stringByReplacingOccuranceOfString:@"" withString:@"" , it give me the URL I wanted likeémp Page - Open.html However its not opening in UIWebView but amazingly it opens in Safari & FireFox perfect. Even I open unencoded URL its automatically converts and open the page I'm looking for.

I've google for URL encoding & it points me to different results I already checked but no results help me out!! I tried different functions answers in different URL encoding question but it just changed all special characters and make my URL like, which can't open in UIWebView and even in any browser.

It gives the following Error Log in UIWebView delegate

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error { }

Error Code : 101 & Description : Error Domain=WebKitErrorDomain Code=101 "The operation couldn’t be completed. (WebKitErrorDomain error 101.)" UserInfo=0x6e4cf60 {}

On StackOverflow
Submit Answer!
None of these answers doing it for you?

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.


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


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]

NSString *url = @"émp.html";

[webView loadHTMLString:[NSString stringWithFormat:
                         [[[NSString alloc]

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 (

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 (

Again, don't forget proper memory management.

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:

Hope that helps.

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

NSString* strURL = @"é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!!!

This may useful to someone who's reach to this question for URL encoding, as my question likely different which has been solved and accepted, this is the way I used to do encoding,

-(NSString *)encodeURL:(NSString *)urlString
    CFStringRef newString = CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)urlString, NULL, CFSTR("!*'();:@&=+@,/?#[]"), kCFStringEncodingUTF8);
    return (NSString *)CFBridgingRelease(newString);

You can try this

NSString *url = @" how are you";

NSString* encodedUrl = [url stringByAddingPercentEscapesUsingEncoding:

can you please Try this out.

    //yourURL contains your Encoded URL
    yourURL = [yourURL stringByReplacingOccurrencesOfString:@" " withString:@"%20"];
    yourURL = [yourURL stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    NSLog(@"Keyword:%@ is this",yourURL);

I am not sure,but I have solved using this in my case. Hope this will solve yours.

You probably need to break the URL down into it's constituent parts and then URL encode the host and path but not the scheme. Then put it back together again.

Create an NSURL with the string and then use the methods on it such as host, scheme, path, query, etc to pull it apart. Then use CFURLCreateStringByAddingPercentEscapes to encode the parts and then you can put them back together again into a new NSURL.

+(NSString*) urlEncode :(NSString *)connection_url{

    if(connection_url == NULL || [connection_url length] == 0){
        return connection_url;

    int index = 0;

    int size = [connection_url length];

    NSMutableString* encodedSting = [[NSMutableString alloc] initWithCapacity:size];

    char c;
    for(;index < size ;index++){
        c =[connection_url characterAtIndex:index];

        if (
            (c >= ',' && c <= ';')
            || (c >= 'A' && c <= 'Z')
            || (c >= 'a' && c <= 'z')
            || c == '_'
            || c == '?'
            || c == '&'
            || c == '=') {

            [encodedSting appendFormat:@"%c",c];

        } else {
            [encodedSting appendString:@"%"];
            int x = (int)c;
            [encodedSting appendFormat:@"%02x", x];



    return [encodedSting autorelease];

Similar Questions
ios : How to get photo url which is deleted in
i am having issue in my app the app is photo related in my app i have required photo url which is deleted via photoapp is there any way to find in our app that which photo is deleted in photoapp thanks in advance ...
Read more

IOS How to get complete URL of current selected audio track in IPHONE in MPMediaPickerController
in following this method voidmediapicker mpmediapickercontroller mediapicker didpickmediaitemsmpmediaitemcollection mediaitemcollection i can get the current selected audio file my question is how to get complete url for this selected ...
Read more

iOS : How to do proper paging in UIScrollView?
ive a uiscrollview of size 320160 im adding some uiimageview into it which are of size 213160 the first uimageview starting from 54 x and so on ive added a space of 50 in between each uiimageview ive also enabled pagingenable in ib amp in cod...
Read more

How do I do URL encoding of ASCII characters?
im using ruby to extract a url of a file to download and download it the file name has utf8 characters ex wwwdomaincomÖÇÄÜ360ÓïÒôÖúÀítxt when trying to download the above url it fails using uriescape produces a uri that also do...
Read more

iOS : How to do proper unicode escape conversion for NSString?
before start reading the question youve to know this so itll be easy for you to understand the problem ive two strings verrà and verrà see last character in both the strings the only difference ive these two strings verrà blah blah and v...
Read more

iOS: how do you use URL as names of file?
i mean how to encode the url so that it can be converted to a string compatible as a file name and also it can be decoded back to original url ...
Read more

How to avoid default URL encoding in ASP.NET MVC Html Helpers like RouteLink
i want my url like this httpdomaincomtag高兴 my route mapping routesmaproutetag tagname new controller tag actionindex but htmlroutelink will encode the parameters as default if i use htmlroutelink in my view the generated html is lt...
Read more

How can I disable URL-encoding of cookies in Rails
i have a rails application that has to coexist with a very old legacy application the legacy application looks for a cookie that has a value containing a specific string of characters unfortunately the characters in the legacy cookie often co...
Read more

With iOS, how to check if URL is empty
im loading an json but i want to check of the url in the json is empty sometimes the id is empty how can i check ifurl how to check if empty else error terminating app due to uncaught exception nsrangeexception reason nsarrayi obje...
Read more

Zend Framework: How to assemble proper url when in directory
how can i force zend router to assemble proper urls when the site is running under a directory heres what i mean thisgtviewgturlarraycontroller gt controller action gt action null true would usually return something like controlleraction ...
Read more

How to decode a url encoding string on Windows Mobile?
i have received an url encoding string from the server eg http3a2f2fstaticcsbewcom2f2fcreative2fpdtestpptv2f320x60png i want to decode it to normal url string i find this method but this doesnt work on compact framework string url systemweb...
Read more

How should my URL encoding look if I enter it manually?
i want to fill in a form on a website from java i used charles proxy to determine that pressing the register button on this form sends a url encoded http post request for example if the website were httpsappsbusinesscomregister then the ht...
Read more