How to use special character in NSURL?

Solution 1:

Swift 2

let original = "http://www.geonames.org/search.html?q=Aïn+Béïda+Algeria&country="
if let encodedString = original.stringByAddingPercentEncodingWithAllowedCharacters(
    NSCharacterSet.URLFragmentAllowedCharacterSet()),
    url = NSURL(string: encodedString) 
{
    print(url)
}

Encoded URL is now:

"http://www.geonames.org/search.html?q=A%C3%AFn+B%C3%A9%C3%AFda+Algeria&country="

and is compatible with NSURLSession.

Swift 3

let original = "http://www.geonames.org/search.html?q=Aïn+Béïda+Algeria&country="
if let encoded = original.addingPercentEncoding(withAllowedCharacters: .urlFragmentAllowed),
    let url = URL(string: encoded)
{
    print(url)
}