iOS: load an image from url

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

    SWIFT 5.0 + fetch on background

    private func fetchImage(_ photoURL: URL?) {
    
        guard let imageURL = photoURL else { return  }
    
        DispatchQueue.global(qos: .userInitiated).async {
            do{
                let imageData: Data = try Data(contentsOf: imageURL)
    
                DispatchQueue.main.async {
                    let image = UIImage(data: imageData)
                    self.userImageView.image = image
                    self.userImageView.sizeToFit()
                    self.tableView.reloadData()
                }
            }catch{
                print("Unable to load data: \(error)")
            }
        }
    }
    

提交回复
热议问题