我想将下面的String转换为URL
www.mydomain.com/key=अक्षय
我尝试了let urlToSend = URL(string: "www.mydomain.com/key=अक्षय")!
,但它返回零。
我从textField获得了'षक्षय'关键字,它可以是任何本地语言。
它适用于英语但不能使用当地语言。
我使用let url = URL(string: "www.mydomain.com")?.appendingPathComponent("key=अक्षय")
它给出了www.mydomain.com/key=%E0%A4%85%E0%A4%95%E0%A5%8D%E0%A4%B7%E0%A4%AF
但现在我想www.mydomain.com/key=%E0%A4%85%E0%A4%95%E0%A5%8D%E0%A4%B7%E0%A4%AF
到www.mydomain.com/key=अक्षय
使用URL作为字符串时,您应该将它们编码为URL有效;编码URL的最流行的例子之一是“”(空格)将被编码为“%20”。
因此,在您的情况下,您的网址的编码值应为:
www.mydomain.com%2Fkey=%E0%A4%85%E0%A4%95%E0%A5%8D%E0%A4%B7%E0%A4%AF
正如您所注意到的那样,key
的价值发生了变化
来自:“再生”
塔哈:%0%4%0%0%4%95%0%0%0%4%0%4%
这将使URL有效。
如何:
你可以得到上面这样的结果:
let string = "www.mydomain.com/key=अक्षय"
if let encodedString = string.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed), let url = URL(string: encodedString) {
print(url) // www.mydomain.com%2Fkey=%E0%A4%85%E0%A4%95%E0%A5%8D%E0%A4%B7%E0%A4%AF
}
请注意,为了安全起见,编码字符串和url都有可选绑定。
解码网址:
您还可以返回原始未编码的URL(解码它),如下所示:
let decodedString = "www.mydomain.com%2Fkey=%E0%A4%85%E0%A4%95%E0%A5%8D%E0%A4%B7%E0%A4%AF"
if let unwrappedDecodedString = decodedString.removingPercentEncoding {
print(unwrappedDecodedString) // www.mydomain.com/key=अक्षय
}
再次,可选绑定是安全的。
您需要对URL进行编码。
let urlString = "www.mydomain.com/key=अक्षय".addingPercentEncoding(withAllowedCharacters: .urlPathAllowed)
let url = URL(string: urlString!)
let decodedUrl = urlString?.removingPercentEncoding
请记住,您不应强制解包URL和字符串,如果let或guard语句使用。
试试这件事:
let strURL = "www.mydomain.com/key=अक्षय".addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)
let url = URL(string: strURL!)
或者您可以使用:
let strURL = "www.mydomain.com/key=अक्षय".addingPercentEncoding(withAllowedCharacters: .urlPathAllowed)
let url = URL(string: strURL!)
您可以使用appendingPathComponent
逐个构建URL,而不是明确处理百分比编码:
let url = URL(string: "www.mydomain.com")?.appendingPathComponent("key=अक्षय")
// www.mydomain.com/key=%E0%A4%85%E0%A4%95%E0%A5%8D%E0%A4%B7%E0%A4%AF
Swift3.0
let baseUrl = "www.mydomain.com/key=अक्षय" // base url
let encodedUrl : String! = baseUrl.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed) // remove the spaces in the url string
let typeUrl = URL(string: encodedUrl)! // convert the string into url
print(typeUrl) // www.mydomain.com/key=%E0%A4%85%E0%A4%95%E0%A5%8D%E0%A4%B7%E0%A4%AF
用于检查目的
if let unwrappedDecodedString = encodedUrl.removingPercentEncoding {
print(decodedString) // www.mydomain.com/key=अक्षय
}