问题复现
let path = "http://..."
print("path:" + path)
if let url = URL.init(string: path) {
imgV.sd_setImage(with: url, completed: nil)
}else{
print("路径无法转换成url")
}
如果
path
中含有中文,则string
转url
无法成功
查看官方解读:
/// Initialize with string.
///
/// Returns `nil` if a `URL` cannot be formed with the string (for example, if the string contains characters that are illegal in a URL, or is an empty string).
public init?(string: String)
官方给出的解释是:String转Url出错有两种可能性:String为空、含有非法字符
很明显我们的path
不为空,那么就是含有非法字符。
解决方案
path = path.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
修复后代码如下:
let path = "http://..."
path = path.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
print("path:" + path)
if let url = URL.init(string: path) {
imgV.sd_setImage(with: url, completed: nil)
}else{
print("路径无法转换成url")
}
网友评论