如果让 url = URL(string:"") 对于 .JPEG 图像总是失败
if let url = URL(string:"") always getting fail for .JPEG images
if let url = URL(string: "https://omsoftware.org/sorora/public/profile_images/kapil borkar_199.jpeg"){}
当文件扩展名为 .jpeg 时总是失败。我试过 .png 它只工作正常。
当扩展名是 .jpeg 时,URL(string:) 没有给出 url 对象。请帮忙。
如您所见,url 中有空格
所以你可以使用 like
let urlStr = "your Url Strting".replacingOccurrences(of: " ", with: "%20")
if let url = URL(string: urlStr){}
您需要对 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(withAllowedCharacters:)
Returns a new string made from the receiver by replacing all
characters not in the specified set with percent-encoded characters.
参考this了解更多addingPercentEncoding(withAllowedCharacters:)
方法。
if let url = URL(string: "https://omsoftware.org/sorora/public/profile_images/kapil borkar_199.jpeg"){}
当文件扩展名为 .jpeg 时总是失败。我试过 .png 它只工作正常。 当扩展名是 .jpeg 时,URL(string:) 没有给出 url 对象。请帮忙。
如您所见,url 中有空格 所以你可以使用 like
let urlStr = "your Url Strting".replacingOccurrences(of: " ", with: "%20")
if let url = URL(string: urlStr){}
您需要对 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(withAllowedCharacters:)
Returns a new string made from the receiver by replacing all characters not in the specified set with percent-encoded characters.
参考this了解更多addingPercentEncoding(withAllowedCharacters:)
方法。