2015-04-01 20 views
14

Muszę wysłać adres URL w języku arabskim, więc muszę go zakodować przed umieszczeniem go w adresie URL. Używam kodu Swift.Kodowanie adresu URL za pomocą kodu Swift

Poniżej jest przykład tego, co naprawdę trzeba

var s = "www.example.com/السلام عليكم" 

let url = NSURL(string : s) 

tak więc słowo (السلام عليكم) jest alfabetem arabskim, że to, co chcę wysłać.

+0

http://stackoverflow.com/a/28734595/2303865 –

+0

dostałeś odpowiedź? – Jan

Odpowiedz

6

Musisz zakodować URL jak masz napisane. Można to zrobić za pomocą tej metody strun:

stringByAddingPercentEscapesUsingEncoding(NSStringEncoding) 

Tak Twój kod będzie:

var s = "www.example.com/السلام عليكم" 
// you may add check before force unwrapping 
let url = NSURL(string : s.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!) 
24

Swift 2,0

let urlwithPercentEscapes = myurlstring.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet()) 

Swift 3,0

let urlwithPercentEscapes = myurlstring.addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlQueryAllowed()) 

Swift 3,1

let urlwithPercentEscapes = myurlstring.addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlQueryAllowed) 
+3

Swift 3 powinien: let urlwithPercentEscapes = myurlstring.addingPercentEncoding (withAllowedCharacters: NSCharacterSet.urlQueryAllowed) bez nawiasów po NSCharacterSet.urlQueryAllowed, ponieważ jest właściwością, a nie funkcją. – Benjamin

7

Aby poprawić @Druva's answer utworzyć przedłużeniu gdzieś w projekcie

Swift 2,0

extension String 
{ 
    func encodeUrl() -> String 
    { 
     return self.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet()) 
    } 
func decodeUrl() -> String 
    { 
     return self.stringByRemovingPercentEncoding 
    } 

} 

Swift 3.0

extension String 
    { 
     func encodeUrl() -> String 
     { 
      return self.addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlQueryAllowed()) 
     } 
    func decodeUrl() -> String 
     { 
      return self.stringByRemovingPercentEncoding 
     } 

    } 
0

Musisz zakodować ten ciąg, ponieważ zawiera on znaki specjalne.

var s = "www.example.com/السلام عليكم" 
let encodedLink = s.addingPercentEncoding(withAllowedCharacters: .urlFragmentAllowed) 
let encodedURL = NSURL(string: encodedLink!)! as URL 

gdzie encodedURL jest ostateczne URL

Powiązane problemy