我需要用阿拉伯语发送一个URL,所以我需要在将它放入URL之前进行编码。我正在使用Swift代码。使用swift代码编码网址
下面是一个例子我真正需要的
var s = "www.example.com/السلام عليكم"
let url = NSURL(string : s)
所以字(السلامعليكم)是什么我想给阿拉伯字符。
我需要用阿拉伯语发送一个URL,所以我需要在将它放入URL之前进行编码。我正在使用Swift代码。使用swift代码编码网址
下面是一个例子我真正需要的
var s = "www.example.com/السلام عليكم"
let url = NSURL(string : s)
所以字(السلامعليكم)是什么我想给阿拉伯字符。
您发送该URL
你需要为你写编码网址前编码这个URL。你可以用字符串的方法做到这一点:
stringByAddingPercentEscapesUsingEncoding(NSStringEncoding)
所以,你的代码将是:
var s = "www.example.com/السلام عليكم"
// you may add check before force unwrapping
let url = NSURL(string : s.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!)
雨燕2.0
let urlwithPercentEscapes = myurlstring.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())
雨燕3.0
let urlwithPercentEscapes = myurlstring.addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlQueryAllowed())
雨燕3.1
let urlwithPercentEscapes = myurlstring.addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlQueryAllowed)
Swift 3应该是:让urlwithPercentEscapes = myurlstring.addingPercentEncoding(withAllowedCharacters:NSCharacterSet.urlQueryAllowed)在NSCharacterSet.urlQueryAllowed之后没有圆括号,因为它是一个属性而不是函数。 – Benjamin 2016-11-04 09:39:44
为了提高@Druva's answer 项目
斯威夫特的地方创建一个推广2.0
extension String
{
func encodeUrl() -> String
{
return self.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())
}
func decodeUrl() -> String
{
return self.stringByRemovingPercentEncoding
}
}
雨燕3.0
extension String
{
func encodeUrl() -> String
{
return self.addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlQueryAllowed())
}
func decodeUrl() -> String
{
return self.stringByRemovingPercentEncoding
}
}
您需要对此字符串进行编码,因为它包含特殊字符。
var s = "www.example.com/السلام عليكم"
let encodedLink = s.addingPercentEncoding(withAllowedCharacters: .urlFragmentAllowed)
let encodedURL = NSURL(string: encodedLink!)! as URL
其中encodedURL是您的最终网址
http://stackoverflow.com/a/28734595/2303865 – 2015-04-01 19:01:44
你得到的答案? – Jan 2016-10-12 05:22:04