Search code examples
iosnsurl

URLWithString: returns nil even when constructed with a correct URL


I'm trying to build a NSURL from a string like this :

NSString *urlString = self.providerData[@"LogoUrl"];

NSURL *url = [NSURL URLWithString:urlString];

NSLog(@"logo url string : %@ - logo url : %@", urlString, url);

Here's the output :

logo url string :  http://cdn.site-annonce.fr/img/mobile/multipublish/TopAnnonces.png - logo url : (null)

The doc says it can return nil if the URL is malformed. What am I missing ?


Solution

  • If we take the output literally, there's leading whitespace (two blanks) even though the format string contains only one.

    Fix with :

    urlString = [urlString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];