创建一个加载图像/活动指示器,直到图像迅速显示在屏幕上 [英] create a loading image/ activity indicator, until the image is shown in the screen in swift

查看:47
本文介绍了创建一个加载图像/活动指示器,直到图像迅速显示在屏幕上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

i want to show an activity indicator in the screen while the image is being downloaded from a website url then show in the images.image this is my code below. everytime i download image it print the status right away and the activity indicator never appear. been searching through the web but i still didnt understand. please help

 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()
}

推荐答案

您遇到了此问题,因为:

You got this problem, because:

  1. 您没有将 activityIndi​​cator 添加到任何视图
  2. 您在 completionHandler 块中配置了 activityIndi​​cator
  1. You didn't add the activityIndicator to any views
  2. You configured the activityIndicator in the completionHandler block

让我们在 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

And start to animate it before resuming the 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()
}

结果!

这篇关于创建一个加载图像/活动指示器,直到图像迅速显示在屏幕上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆