使用swift代码编码url

我需要用阿拉伯语发送一个URL,所以我需要在将它放入URL之前对其进行编码。 我正在使用Swift代码。

以下是我真正需要的一个例子

var s = "www.example.com/السلام عليكم" let url = NSURL(string : s) 

所以这个词(السلامعليكم)是我想发送的阿拉伯字符。

Swift 2.0

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

斯威夫特3

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

为了改善@ Druva的答案 ,在项目的某个地方创建一个扩展

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

你需要编写url来编写代码。 您可以使用该字符串方法执行此操作:

 stringByAddingPercentEscapesUsingEncoding(NSStringEncoding) 

所以你的代码将是:

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

您需要对此字符串进行编码,因为它包含特殊字符。

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

其中encodedURL是您的最终URL

swift 4我们面临着通过这种方式解决的同样问题

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

您必须在发送此URL之前对此URL进行编码