20

I need to send an URL in Arabic language, so I need to encode it before I put it in URL. I am using Swift code.

Below is an example what i really need

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

let url = NSURL(string : s)

So the word (السلام عليكم) is in Arabic characters that what I want to send.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
inanva
  • 223
  • 1
  • 3
  • 9

6 Answers6

35

Swift 2.0

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

Swift 3

let urlwithPercentEscapes = myurlstring.addingPercentEncoding( withAllowedCharacters: .urlQueryAllowed)
rmaddy
  • 314,917
  • 42
  • 532
  • 579
yarlg
  • 3,481
  • 3
  • 20
  • 20
  • 3
    Swift 3 should be: let urlwithPercentEscapes = myurlstring.addingPercentEncoding( withAllowedCharacters: NSCharacterSet.urlQueryAllowed ) without parentheses after NSCharacterSet.urlQueryAllowed because it is a property not a function. – Benjamin Nov 04 '16 at 09:39
11

To improve @Druva's answer create an extention somewhere in the project

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: .urlQueryAllowed)
        }
    func decodeUrl() -> String
        {
            return self.stringByRemovingPercentEncoding
        }

    }
rmaddy
  • 314,917
  • 42
  • 532
  • 579
Vyacheslav
  • 26,359
  • 19
  • 112
  • 194
6

You need to encode url as you have written. You can do so with that string method:

stringByAddingPercentEscapesUsingEncoding(NSStringEncoding)

So your code will be:

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

You need to encode this string as it contains special characters.

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

where encodedURL is your final URL

Gary G
  • 31
  • 2
1

swift 4 we face the same problem it solved by this way

extension String { 
var fixedArabicURL: String?  {
       return self.addingPercentEncoding(withAllowedCharacters: CharacterSet.alphanumerics
           .union(CharacterSet.urlPathAllowed)
           .union(CharacterSet.urlHostAllowed))
   } }
-2

you have to Encode this URL before sending this URL