简体   繁体   English

编码 url swift withAllowedCharacters not working encoding %20 as %2520(意味着将 % 编码为 %25)

[英]encode url swift withAllowedCharacters not working encoding %20 as %2520 (means encoding % as %25)

Following is my code for URL encoding以下是我的 URL 编码代码

extension String {
var encoded: String {
    return self.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? ""
  }
}

But I am facing issue if url contains %20.但如果 url 包含 %20,我将面临问题。 it is encoding it as %2520 although I have added urlQueryAllowed尽管我添加了urlQueryAllowed ,但它将其编码为 %2520

Original url: https://mydomain.in/retailers_data_v2/retailer/320/17372-Tea%20Coffee%20Vending%20Machine.JPG原装url: https://mydomain.in/retailers_data_v2/retailer/320/17372-Tea%20Coffee%20Vending%20Machine.JPG

Encoded url: https://mydomain.in/retailers_data_v2/retailer/320/17372-Tea%2520Coffee%2520Vending%2520Machine.JPG编码 url: https://mydomain.in/retailers_data_v2/retailer/320/17372-Tea%2520Coffee%2520Vending%2520Machine.JPG

If you have an already encoded URL String, you first need to remove percent encoding before applying it again.如果您有一个已经编码的 URL 字符串,您首先需要在再次应用之前删除百分比编码。

If you aren't sure whether the URL you have is already encoded or not, you can simply use an if let on removingPercentEncoding and depending on its result, either call addingPercentEncoding on the original URL or on the one that you removed the encoding from.如果您不确定您拥有的 URL 是否已经编码,您可以简单地使用if let on removingPercentEncoding并根据其结果,在原始 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)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM