一尘不染

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

swift

我的应用程序正在使用这样的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")
        }

但是尝试从该地址获取数据时出现错误,尽管当我使用野生动物园去链接时:“
http://www.geonames.org/search.html?q
=Aïn+Béïda+ Algeria&country =“我可以看到数据。我该如何解决?


阅读 224

收藏
2020-07-07

共1个答案

一尘不染

迅捷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

迅捷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)
}
2020-07-07