iOS: load an image from url

前端 未结 9 1403
生来不讨喜
生来不讨喜 2020-12-02 14:06

I need to load an image from a url and set it inside an UIImageView; the problem is that I don\'t know the exact size of the image, then how can I show the image correctly?<

9条回答
  •  天涯浪人
    2020-12-02 14:57

    If you prefer you can even move it to an UIImage extension:

    extension UIImage {
        
        //NOTE: This is not thread safe, please run it on a background thread.
        convenience init?(fromFile filePath:String) {
            guard let url = URL(string: filePath) else {
                return nil
            }
            
            self.init(fromURL: url)
        }
        
        //NOTE: This is not thread safe, please run it on a background thread.
        convenience init?(fromURL url:URL) {
            let imageData: Data
            
            do {
                imageData = try Data(contentsOf: url)
            } catch {
                return nil
            }
            
            self.init(data: imageData)
        }
        
    }
    

提交回复
热议问题