Search code examples
swiftnsurlcyrillic

NSURL and russian domains


That's a problem and i cannot find the solution. In my program i try to open Safari with url, and that was ok until the occasion: i tried to link the site with russian host and domain, for example:

let url = "http://карта.рф"
UIApplication.sharedApplication().openURL(NSURL(string: url)!)

Then i have an error:

fatal error: unexpectedly found nil while unwrapping an Optional value

So the class NSURL cannot make an object on a link having russian symbols. I tried to use url.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLFragmentAllowedCharacterSet())! and similar, but the problem is that it change ALL "incorrect" symbols onto others, but it's necessary to link exactly russian sites, in russian domains, which means there are no really incorrect letters in url-address.

I don't believe that the NSURL cannot work with non-english symbols. Can anyone help me?


Solution

  • You need the character set related to the host

    let string = "http://" + "карта.рф".stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet())!
    let url = NSURL(string:string)
    

    If you have to encode also path and query use NSURLComponents and encode the other components separately.

    let components = NSURLComponents()
    components.scheme = "http"
    components.host = "карта.рф".stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet())
    
    let url = components.URL!