swift - 创建加载图像/事件指示器,直到图像快速显示在屏幕上

标签 swift loading

我想在从网站 url 下载图像时在屏幕上显示一个事件指示器,然后在图像中显示。图像这是我下面的代码。每次我下载图像时,它都会立即打印状态,并且事件指示器永远不会出现。一直在网上搜索,但我还是不明白。请帮忙

 let mygroup = DispatchGroup()
 var activityIndicator = UIActivityIndicatorView()

func downloadpic(sender:UIButton){
    let catPictureURL = URL(string: addr)!

    // Creating a session object with the default configuration.
    // You can read more about it here https://developer.apple.com/reference/foundation/urlsessionconfiguration
    let session = URLSession(configuration: .default)

    // Define a download task. The download task will download the contents of the URL as a Data object and then you can do what you wish with that data.

    let downloadPicTask = session.dataTask(with: catPictureURL) { (data, response, error) in
        // The download has finished.
        if let e = error {
            print("Error downloading cat picture: \(e)")
        } else {
            // No errors found.
            // It would be weird if we didn't have a response, so check for that too.
            if let res = response as? HTTPURLResponse {
                // put loading screen here
                self.activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: .white)
                self.activityIndicator.frame = CGRect(x: 0, y: 0, width: 46, height: 46)
                self.activityIndicator.startAnimating()
                self.mygroup.enter()
                print("downloading image")
                print("Downloaded cat picture with response code \(res.statusCode)")
                if let imageData = data {
                    // Finally convert that Data into an image and do what you wish with it.
                     self.images.image = UIImage(data: imageData)
                        self.mygroup.leave()
                        print("image already downloaded")
                        self.activityIndicator.stopAnimating()
                        self.activityIndicator.hidesWhenStopped = true


                    // Do something with your image.
                } else {
                    print("Couldn't get image: Image is nil")
                }
            } else {
                print("Couldn't get response code for some reason")
            }
        }
    }

    downloadPicTask.resume()
}

最佳答案

你遇到这个问题是因为:

  1. 您没有将 activityIndi​​cator 添加到任何 View
  2. 您在 completionHandler block 中配置了 activityIndi​​cator

activityIndi​​cator 中配置 viewDidLoad() 方法:

self.activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: .gray)
self.activityIndicator.frame = CGRect(x: 0, y: 0, width: 46, height: 46)
self.activityIndicator.hidesWhenStopped = true

view.addSubview(self.activityIndicator)

并在恢复 dataTask

之前开始对其进行动画处理
self.activityIndicator.startAnimating()

然后,在 completionHandler

中停止它
self.activityIndicator.stopAnimating()

最终代码:

let mygroup = DispatchGroup()
var activityIndicator = UIActivityIndicatorView()

override func viewDidLoad() {
    super.viewDidLoad()

    self.activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: .gray)
    self.activityIndicator.frame = CGRect(x: 0, y: 0, width: 46, height: 46)
    self.activityIndicator.hidesWhenStopped = true

    view.addSubview(self.activityIndicator)
}

func downloadpic(sender: UIButton) {
    let catPictureURL = URL(string: addr)!

    // Creating a session object with the default configuration.
    // You can read more about it here https://developer.apple.com/reference/foundation/urlsessionconfiguration
    let session = URLSession(configuration: .default)

    // Define a download task. The download task will download the contents of the URL as a Data object and then you can do what you wish with that data.

    self.activityIndicator.startAnimating()

    let downloadPicTask = session.dataTask(with: catPictureURL) { (data, response, error) in
        // The download has finished.
        if let e = error {
            print("Error downloading cat picture: \(e)")
        } else {
            // No errors found.
            // It would be weird if we didn't have a response, so check for that too.
            if let res = response as? HTTPURLResponse {
                // put loading screen here

                self.mygroup.enter()
                print("downloading image")
                print("Downloaded cat picture with response code \(res.statusCode)")
                if let imageData = data {
                    // Finally convert that Data into an image and do what you wish with it.
                    self.images.image = UIImage(data: imageData)
                    self.mygroup.leave()
                    print("image already downloaded")
                    self.activityIndicator.stopAnimating()

                    // Do something with your image.
                } else {
                    print("Couldn't get image: Image is nil")
                }
            } else {
                print("Couldn't get response code for some reason")
            }
        }
    }

    downloadPicTask.resume()
}

结果!

enter image description here

关于swift - 创建加载图像/事件指示器,直到图像快速显示在屏幕上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43404129/

相关文章:

ios - 如何在 iOS Swift 中从可编码模型创建嵌套的 json?

import - 如何在 Swift 中定义自定义 UIGestureRecognizer?

ios - 带有自定义声音的 UNMutableNotificationContent

extjs - 在 ExtJS 中显示和隐藏加载状态

javascript - 使用 applet 描述符和 javascript 在 jnlp 中轮询 applet 下载进度

javascript - 在 vue js 函数期间显示加载动画

swift - Apollo iOS 代码生成 : Nested use of a fragment in a mutation creates unexpected property types in Fragments struct

compiler-errors - 将代码从 Objective-C 转换为 Swift

javascript - Ember.js 加载模板上的每个模型 Promise 状态

javascript - 如何在发生图像更改事件时显示加载图标。 (没有 jQuery)