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