简体   繁体   English

setImageWith Url完成块Swift iOS

[英]setImageWith Url completion block swift ios

I am new to swift. 我是新手。 I am loading image with url 我正在使用url加载图像

mainImageView.setImageWith(URL(string: ("https:" + (content?.imagePath)!)), placeholderImage: nil)
print("dimensions after loading \(String(describing: mainImageView.image?.size))")

In case, I print the dimensions of the image as shown above then dimensions come out to be 21*6.5. 万一我按上面所示打印图像的尺寸,则尺寸为21 * 6.5。 However, if I wait for sometime and then print the dimensions are 188*109. 但是,如果我等待一段时间再打印,则尺寸为188 * 109。 How do I add a completion block to setImageWith so that I can come to know when image has finished loading? 如何在setImageWith中添加完成块,以便可以知道何时完成图像加载?

You can use Sdwebimage for loading the image with completion block https://github.com/rs/SDWebImage 您可以使用Sdwebimage来加载带有完成块的图像https://github.com/rs/SDWebImage

imageView.sd_setImageWithURL(NSURL(string: urlString), completed: {
                (image, error, cacheType, url) in
                // you can get the image width here...
            })

It is happening because URL will always take a time to load image thats why first you got 21*6.5 dimensions and then got real dimensions 188*109 . 之所以发生这种情况,是因为URL总是需要一些时间来加载图像,这就是为什么首先获得21 * 6.5尺寸,然后获得实际尺寸188 * 109的原因

As best way to prefer 3rd party library SDWebImage that will manage all the thing, You just need to set image URL. 作为首选可管理所有内容的第三方库SDWebImage的最佳方法,只需设置图像URL。

There is method name is 有方法名称是

open func sd_setImage(with url: URL!, placeholderImage placeholder: UIImage!, options: SDWebImageOptions = [], completed completedBlock: SDWebImage.SDWebImageCompletionBlock!)

that has completion block so you can manage whatever you want. 具有完成块,因此您可以管理所需的任何内容。

Convert image URL into data then Data into UIIamge , Here is a function: 将图片URL转换为数据,然后将Data转换为UIIamge ,这是一个函数:

func getImageFromUrl(_ strUrl: String, completionHandler handler: @escaping (_ img: UIImage) -> Void) {
    DispatchQueue.global(qos: .background).async {
        let url = URL(string: strUrl)
        let dataFromUrl = Data(contentsOf: url!)
        if dataFromUrl == nil {
            return
        }
        DispatchQueue.main.async(execute: {() -> Void in
            handler(UIImage(data: dataFromUrl!))
        })
    })
}

Use This: - 用这个: -

  let imageCache = NSCache<AnyObject, AnyObject>()
 typealias CompletionHandler = (_ success:Bool, _ image:UIImage?) -> Void





 func loadImageUsingCacheWithUrlString(_ urlString: 
 String,completionHandler: @escaping CompletionHandler) {
let image = UIImage()

    //check cache for image first
    if let cachedImage = imageCache.object(forKey: urlString as AnyObject) as? UIImage {
        image = cachedImage
        completionHandler(true, image!)
        return
    }

    if urlString.characters.count == 0 {
        completionHandler(false, image)
        return
    }

    //otherwise fire off a new download
    let url = URL(string: urlString)

    URLSession.shared.dataTask(with: url!, completionHandler: { (data, response, error) in

        //download hit an error so lets return out
        if error != nil {
            print(error ?? "")
            completionHandler(false,nil)
            return
        }

        DispatchQueue.main.async(execute: {
            if let downloadedImage = UIImage(data: data!) {
                image = downloadedImage
                imageCache.setObject(downloadedImage, forKey: urlString as AnyObject)                    

                completionHandler(true,image)
            }
        })

    }).resume()


}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM