How to deal with URL with spaces in it?

objective-c

Solution

You can percent-escape characters which aren't valid inside an URL:

NSURL *url = [NSURL URLWithString:
    [urlCached stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];

This is easy but not always correct; for escaping valid URL special chars (`%`, `&`, `?`, `:`) as well, use the `CFURLCreateStringByAddingPercentEscapes()` function.

Problem

``` NSString * urlCached = URL.CacheImageURL; NSURL * url = [NSURL URLWithString:urlCached]; NSData * data=[NSData dataWithContentsOfURL:url]; ``` It works fine for most URL. However, if URL contains space such as http://google.com/Hello World.htm then it won't work. What should I do for such URLs?

Original source