UIImageView, Load UIImage from remote URL

2019-08-01 17:10发布

问题:

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!

回答1:

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


回答2:

The method fileURLWithPath opens file from file system. The file address is prepended with file://. You can print the url string.

From Apple documentation about + (NSURL *)fileURLWithPath:(NSString *)path;

The path that the NSURL object will represent. path should be a valid system path, and must not be an empty path. If path begins with a tilde, it must first be expanded with stringByExpandingTildeInPath. If path is a relative path, it is treated as being relative to the current working directory.

Here is one of a few possible solutions:

let imageName = "http://verona-api.municipiumstaging.it/system/images/image/image/22/app_1920_1280_4.jpg"

func loadImage(with address: String) {

    // Perform on background thread
    DispatchQueue.global().async {

        // Create url from string address
        guard let url = URL(string: address) else {
            return
        }

        // Create data from url (You can handle exeption with try-catch)
        guard let data = try? Data(contentsOf: url) else {
            return
        }

        // Create image from data
        guard let image = UIImage(data: data) else {
            return
        }

        // Perform on UI thread
        DispatchQueue.main.async {
            let imageView = UIImageView(image: image)
            /* Do some stuff with your imageView */
        }
    }
}

loadImage(with: imageName)

It's best practice if you just send a completion handler to perform on main thread to loadImage(with:).



回答3:

Here the url is not of the local system but of the server.

  let url = URL(fileURLWithPath: "http://verona-api.municipiumstaging.it/system/images/image/image/22/app_1920_1280_4.jpg")

Here the url created is of file which is locally on the device. Create url like this:-

  url = URL(string: "http://verona-api.municipiumstaging.it/system/images/image/image/22/app_1920_1280_4.jpg")