为了工作,我们有一家第三方公司为某些功能提供 JSON API。 JSON 包含我尝试使用 URL(string: ...)
在代码中映射的网址,但这在某些带有空格的网址上失败。
例如:
var str = "https://google.com/article/test test.html"
let url = URL(string: str) //nil
我应该要求第三方对其 URL 进行编码吗?
这是正常的还是我应该尝试自己添加编码? 我认为对自己进行编码很困难,因为路径的编码方式应该与查询不同,并且主机不应该进行编码等。
还是我想太多了?
最佳答案
如果 URL 的路径
中包含空格,请使用 addingPercentEncoding(withAllowedCharacters
) 传递 urlPathAllowed
字符集对字符进行转义:
let str = "https://google.com/article/test test.html"
if let escapedString = str.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlPathAllowed),
let url = URL(string:escapedString) {
print(url)
} else {
print("url \(str) could not be encoded")
}
关于swift - 使用 swift 读取 JSON api 中的 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45021175/