iOS: load an image from url

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

    IN SWIFT 3.0

    The main thread must be always remain free so it serves the user interface and user interactions.

    class ViewController: UIViewController {
    
    @IBOutlet weak var imageView: UIImageView!
    
    private func fetchImage() {
        let imageURL = URL(string: "https://i.stack.imgur.com/9z6nS.png")
        var image: UIImage?
        if let url = imageURL {
            //All network operations has to run on different thread(not on main thread).
            DispatchQueue.global(qos: .userInitiated).async {
                let imageData = NSData(contentsOf: url)
                //All UI operations has to run on main thread.
                DispatchQueue.main.async {
                    if imageData != nil {
                        image = UIImage(data: imageData as! Data)
                        self.imageView.image = image
                        self.imageView.sizeToFit()
                    } else {
                        image = nil
                    }
                }
            }
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        fetchImage()
    }
    
    }
    

提交回复
热议问题