美文网首页
swift string转url失败的解决方案

swift string转url失败的解决方案

作者: 本帅不良 | 来源:发表于2020-08-26 15:42 被阅读0次

问题复现

let path = "http://..."
print("path:" + path)
if let url = URL.init(string: path) {
      imgV.sd_setImage(with: url, completed: nil)
}else{
      print("路径无法转换成url")
}

如果 path中含有中文,则stringurl无法成功

查看官方解读:

    /// 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")
}

相关文章

网友评论

      本文标题:swift string转url失败的解决方案

      本文链接:https://www.haomeiwen.com/subject/ksxfsktx.html