iOS: load an image from url

前端 未结 9 1401
生来不讨喜
生来不讨喜 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:46

    To download Asynchronous image with Kingfisher library you can follow this step,url :https://github.com/onevcat/Kingfisher:

     func imageFromUrl(_ urlString: String) {
            if let url = URL(string: urlString) {
                ImageDownloader.default.downloadImage(with: url, options: [], progressBlock: nil) {
                    (image, error, url, data) in
                    DispatchQueue.main.async {
                        self.imageView.image = image
                    }
                }
            }
        }
    

    You can also download image with default URLSession.shared.dataTask

     func imageFromUrl(_ urlString: String) {
            if let url = URL(string: urlString) {
                let request = URLRequest(url: url)
                URLSession.shared.dataTask(with: request) {(data,response,error) in
                    if let imageData = data as Data? {
                        if let img = UIImage(data: imageData){
                           DispatchQueue.main.async {
                           self.imageView.image = img
                           }
                        }
                    }
                }
            }
        }
    

提交回复
热议问题