我的应用程序正在使用这样的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 =”我可以看到数据。我该如何解决?

最佳答案

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

关于swift - 如何在NSURL中使用特殊字符?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41855262/

10-13 04:38