Loading/Downloading image from URL on Swift

前端 未结 30 3186
感动是毒
感动是毒 2020-11-21 05:39

I\'d like to load an image from a URL in my application, so I first tried with Objective-C and it worked, however, with Swift, I\'ve a compilation error:

30条回答
  •  不要未来只要你来
    2020-11-21 05:54

    I wrapped the code of the best answers to the question into a single, reusable class extending UIImageView, so you can directly use asynchronous loading UIImageViews in your storyboard (or create them from code).

    Here is my class:

    import Foundation
    import UIKit
    
    class UIImageViewAsync :UIImageView
    {
    
        override init()
        {
            super.init(frame: CGRect())
        }
    
        override init(frame:CGRect)
        {
            super.init(frame:frame)
        }
    
        required init(coder aDecoder: NSCoder) {
            super.init(coder: aDecoder)
        }
    
        func getDataFromUrl(url:String, completion: ((data: NSData?) -> Void)) {
            NSURLSession.sharedSession().dataTaskWithURL(NSURL(string: url)!) { (data, response, error) in
                completion(data: NSData(data: data))
            }.resume()
        }
    
        func downloadImage(url:String){
            getDataFromUrl(url) { data in
                dispatch_async(dispatch_get_main_queue()) {
                    self.contentMode = UIViewContentMode.ScaleAspectFill
                    self.image = UIImage(data: data!)
                }
            }
        }
    }
    

    and here is how to use it:

    imageView.downloadImage("http://www.image-server.com/myImage.jpg")
    

提交回复
热议问题