Search code examples
iosswifturluiimageviewuiimage

UIImageView, Load UIImage from remote URL


This problems it's driving me crazy... I have this string url:
"verona-api.municipiumstaging.it/system/images/image/image/22/app_1920_1280_4.jpg" and I have to load this image in my imageView.

this is my code :

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

This throw the exception :

No such file or directory.

But if I search this url with a browser I can see the image correctly!


Solution

  • You are using wrong method to create URL. Try URLWithString instead of fileURLWithPath. fileURLWithPath is used to get image from local file path not from internet url.

    or

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