简体   繁体   English

如何在Swift中下载数据时不阻止UI

[英]How not to block UI while downloading data in Swift

I have question regarding DispatchQueue. 我对DispatchQueue有疑问。 In one of my view controllers, I do need to download an image from web and display it on a UIImageView. 在我的一个视图控制器中,我确实需要从Web下载图像并将其显示在UIImageView上。 While the app downloading the image, I am trying not to block the UI using DispatchQueue. 当应用程序下载图像时,我尝试不使用DispatchQueue阻止UI。 The below code does not seem to work. 以下代码似乎无效。 Can anyone explain why? 谁能解释为什么? and how to do this properly? 以及如何正确执行此操作?

let store_id = self.store!._id

DispatchQueue.global().async {
let imageUrl = URL(string: "www.image.com")
self.storeImageData = imageUrl != nil ? try? Data(contentsOf:imageUrl!) : nil

    if self.storeImageData != nil {
        DispatchQueue.main.async {
            self.topBackgroundImageView.image = UIImage(data:self.storeImageData!)
        }
    }
}

I would not recommend your way of downloading over the network, use either URLSession or Alamofire . 我不建议您使用网络URLSession下载方式,请使用URLSessionAlamofire Here is some code you can follow: 这是您可以遵循的一些代码:

func downloadImageFrom(urlString:String, completion:@escaping(Data?)->()) {
    guard let url = URL(string:urlString) else { return }
    let request = URLRequest(url: url)
    URLSession.shared.dataTask(with: request) { (data, _, err) in
        if err != nil {
            // handle error if any
        }
        // you should check the reponse status
        // if data is a json object/dictionary so decode it
        // if data is regular data then pass it to your callback
        completion(data)
    }.resume()
}

func doWork() {
    DispatchQueue.global(qos: .background).async { [weak self] in
        guard let strongSelf = self else { return } // to avoid reference cycle
        strongSelf.downloadImageFrom(urlString: "http://www.image.com", completion: { (data) in
            if let _data = data {
                // now you have the data
                DispatchQueue.main.async {
                    // display your imageView with the data
                }
            }
        })
    }
}

Hope will helpful to you download an image from web and display it on a UIImageView. 希望对您从Web下载图像并将其显示在UIImageView上有所帮助。

SDWebImage does very aggressive caching by default. SDWebImage默认情况下会进行非常积极的缓存。 It ignores all kind of caching control header returned by the HTTP server and cache the returned images with no time restriction. 它忽略HTTP服务器返回的所有类型的缓存控制标头,并且不受时间限制地缓存返回的图像。 It implies your images URLs are static URLs pointing to images that never change. 这表示您的图片网址是指向不变的图片的静态网址。 If the pointed image happen to change, some parts of the URL should change accordingly. 如果指向的图像发生更改,则URL的某些部分应相应更改。

import SDWebImage

imageView.sd_setImage(with: URL(string: "http://www.image.com/image.jpg"), placeholderImage: UIImage(named: "placeholder.png"))

// Or using this code
[imageView sd_setImageWithURL:[NSURL URLWithString:@"http://www.image.com/image.jpg"]
         placeholderImage:[UIImage imageNamed:@"avatar-placeholder.png"]
                  options:SDWebImageRefreshCached];

Add a progress indicator 添加进度指示器

imageView.sd_setShowActivityIndicatorView(true)
imageView.sd_setIndicatorStyle(.Gray)

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

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