UIImageView,从远程URL加载UIImage

Leo*_*rdo 1 url uiimageview uiimage ios swift

这个问题让我发疯了...我有这个字符串url:
" verona-api.municipiumstaging.it/system/images/image/image/22/app_1920_1280_4.jpg "我必须在我的版本中加载这个图像imageView.

这是我的代码:

do {
    let url = URL(fileURLWithPath: "http://verona-api.municipiumstaging.it/system/images/image/image/22/app_1920_1280_4.jpg")
    let data = try Data(contentsOf: url)
    self.imageView.image = UIImage(data: data)
}
catch{
    print(error)
}
Run Code Online (Sandbox Code Playgroud)

抛出异常:

没有相应的文件和目录.

但是,如果我url用浏览器搜索它,我可以正确地看到图像!

tru*_*duc 10

您使用错误的方法来创建URL.尝试URLWithString而不是fileURLWithPath.fileURLWithPath用于从本地文件路径获取图像而不是从Internet URL获取图像.

要么

do {
    let url = URL(string: "http://verona-api.municipiumstaging.it/system/images/image/image/22/app_1920_1280_4.jpg")
    let data = try Data(contentsOf: url)
    self.imageView.image = UIImage(data: data)
}
catch{
    print(error)
}
Run Code Online (Sandbox Code Playgroud)

  • 您不应将“Data(contentsOf: url)”与远程 URL 一起使用,如文档所述:https://developer.apple.com/documentation/foundation/nsdata/1413892-init 这将阻止当前线程。您应该使用“URLSession.dataTask()”代替。 (2认同)