2015-05-10 17 views
9

La mia applicazione utilizza un NSURL come questo:Come utilizzare caratteri speciali in NSURL?

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

Quando ho provato a fare un compito per ottenere i dati da questo NSURL come questo:

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

ma ho ottenuto l'errore quando si cerca di ottenuto i dati da quell'indirizzo, anche se quando uso Safari vai al link: "http://www.geonames.org/search.html?q = Aïn + Béïda + Algeria & country =" Posso vedere i dati. Come posso ripararlo?

risposta

32

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 codificato è ora:

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

ed è compatibile con 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) 
} 
+0

perché 'URLFragmentAllowedCharacterSet'? c'è anche 'URLHostAllowedCharacterSet',' URLPasswordAllowedCharacterSet', 'URLPathAllowedCharacterSet',' URLQueryAllowedCharacterSet' e 'URLUserAllowedCharacterSet' – fabb

+0

@fabb I avrebbe potuto utilizzare URLQueryAllowedCharacterSet con lo stesso effetto, entrambi i set sono completi. Gli altri set di caratteri URL sono sottoinsiemi di questi due. – Moritz

+0

grazie per le informazioni. Hai qualche fonte per queste informazioni? – fabb