如何在NSURL中使用特殊字符?

时间:2015-05-10 07:50:57

标签: swift nsurl nsurlsession

我的应用程序正在使用NSURL:

var url = NSURL(string: "http://www.geonames.org/search.html?q=Aïn+Béïda+Algeria&country=")

当我尝试从这个NSURL中获取数据的任务时:

    let task = NSURLSession.sharedSession().dataTaskWithURL(url!, completionHandler: { (data: NSData!, response: NSURLResponse!, error: NSError!) -> Void in

        if error == nil {

            var urlContent = NSString(data: data, encoding: NSUTF8StringEncoding)
            println("urlContent \(urlContent!)")
        } else {

            println("error mode")
        }

但是我在尝试从该地址获取数据时遇到错误,尽管当我使用safari时链接:“http://www.geonames.org/search.html?q =Aïn+Béïda+ Algeria& country =”我可以看到数据。我该如何解决这个问题?

1 个答案:

答案 0 :(得分:45)

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)
}

现在编码的URL:

  

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

并与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)
}