This question already has an answer here:
Why can't I convert this String to a URL?
(1个答案)
上个月关门了。
if let url = URL(string: "https://omsoftware.org/sorora/public/profile_images/kapil borkar_199.jpeg"){}

文件扩展名为.jpeg时总是失败。我试过使用.png,它只起作用。
当扩展名为.jpeg时,URL(字符串:)不提供URL对象。请帮忙。

最佳答案

您需要对urlString进行编码以处理空白。对urlString使用addingPercentEncoding(withAllowedCharacters:)方法,即。

let str = "https://omsoftware.org/sorora/public/profile_images/kapil borkar_199.jpeg"

if let urlString = str.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed), let url = URL(string: urlString) {
    //add your code here...
}

addingPercentEncoding(允许字符:)
通过替换all返回从接收器生成的新字符串
不在指定集合中的字符,包含百分比编码字符。
有关addingPercentEncoding(withAllowedCharacters:)方法的更多信息,请参阅this

关于swift - 如果让url = URL(string:“”)对于.JPEG图像总是失败,则,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58408032/

10-11 20:52
查看更多