Search code examples
cocoafoundation

NSURL returns nil when passing a HTTP url with a hostname with non-ascii characters


If you attempt to create a NSURL from this URL, it returns nil (observed on OS X 10.11.6):

http://夜景バーラウンジ-majestic汐留.com/

The URL using the alternate representation of the hostname works fine:

http://xn---majestic-zv4hsg0krlzerfp952e1lybpewawh3b.com/

If all you have is the first version of the URL, is there any way to still make it work with NSURL?


Solution

  • This should work for most cases:

    NSString *urlStr = @"http://夜景バーラウンジ-majestic汐留.com/";
    urlStr = [stringToConvert stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *url = [NSURL URLWithString:urlStr];