以下是我的URL编码代码
extension String {
var encoded: String {
return self.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? ""
}
}
但是如果网址包含%20,我将面临问题。它已将其编码为%2520,尽管我已添加urlQueryAllowed
原始网址:https://mydomain.in/retailers_data_v2/retailer/320/17372-Tea%20Coffee%20Vending%20Machine.JPG
编码网址:https://mydomain.in/retailers_data_v2/retailer/320/17372-Tea%2520Coffee%2520Vending%2520Machine.JPG
如果您已经编码了URL字符串,则首先需要删除百分比编码,然后再应用它。
如果不确定所使用的URL是否已经编码,则可以简单地在if let
上使用removingPercentEncoding
,并根据其结果,对原始URL或对原始URL调用addingPercentEncoding
您从中删除了编码。
let alreadyEncodedURLString = "https://mydomain.in/retailers_data_v2/retailer/320/17372-Tea%20Coffee%20Vending%20Machine.JPG"
if let unencodedURLString = alreadyEncodedURLString.removingPercentEncoding {
unencodedURLString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
} else {
alreadyEncodedURLString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
}