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

时间:2022-09-23 00:13:57

My application is using an NSURL like this:

我的申请使用的是这样的NSURL:

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

When I tried to make a task for getting data from this NSURL like this:

当我尝试从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")
        }

but I got error when trying to got data from that address, although when I using safari go to link: "http://www.geonames.org/search.html?q=Aïn+Béïda+Algeria&country=" I can see the data. How can I fix that?

但是,当我试图从那个地址获取数据时,我却犯了错误,尽管当我使用safari时,它会链接到:http://www.geonames.org/search.html?我能看到数据。我怎样才能解决这个问题呢?

1 个解决方案

#1


37  

Swift 2

斯威夫特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:

URL编码:

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

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

and is compatible with NSURLSession.

与NSURLSession兼容。

Swift 3

斯威夫特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)
}

#1


37  

Swift 2

斯威夫特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:

URL编码:

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

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

and is compatible with NSURLSession.

与NSURLSession兼容。

Swift 3

斯威夫特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)
}