如何在下载图片之前运行活动指示器?

时间:2017-03-01 19:33:05

标签: ios swift indicator activity-indicator

在图像下载之前,我想启动激活指示器。

这是我使用网址的图片下载功能

extension UIImageView {

func downloadImage(from url : String){

    let urlRequest = URLRequest(url: URL(string: url)!)
    let task = URLSession.shared.dataTask(with: urlRequest){(data,response,error)in

        if error != nil {

            print("error...")

        }

        DispatchQueue.main.async {
            self.image = UIImage(data:data!)
        }
    }

    task.resume()
}

我的问题是我该怎么做? (对不起,我的英文不好)

4 个答案:

答案 0 :(得分:3)

您可以在方法中传递一个闭包,该闭包将在下载图像后执行

extension UIImageView {

  func downloadImage(from url : String, completion: ((_ errorMessage: String?) -> Void)?){

    let urlRequest = URLRequest(url: URL(string: url)!)
    let task = URLSession.shared.dataTask(with: urlRequest){ (data,response,error) in

      if error != nil {
        completion?("error...")
      }

      DispatchQueue.main.async {
        self.image = UIImage(data:data!)
        completion?(nil)
      }
    }

    task.resume()
  }
}

并在您的ViewController中

activityIndicator.startAnimating()
imageView.downloadImage(from: "...") { (err) in
  if err != nil {
    // error handler
  }
  self.activityIndicator.stopAnimating()
}

答案 1 :(得分:1)

您可以尝试以下方法

extension UIImageView {

  func downloadImage(from url : String){
    self.activityIndicator.startAnimating()
    let urlRequest = URLRequest(url: URL(string: url)!)
    let task = URLSession.shared.dataTask(with: urlRequest){(data,response,error)in
      if error != nil {
        DispatchQueue.main.async {
          self.activityIndicator.stopAnimating()
        }
        print("error...")
      }
      else {
        DispatchQueue.main.async {
          self.activityIndicator.stopAnimating()
          self.image = UIImage(data:data!)
        }
      }
    }
    task.resume()
  }

  fileprivate var activityIndicator: UIActivityIndicatorView {
    get {
      let activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: .white)
      activityIndicator.hidesWhenStopped = true
      activityIndicator.center = CGPoint(x:self.frame.width/2,
                                     y: self.frame.height/2)
      activityIndicator.stopAnimating()
      self.addSubview(activityIndicator)
      return activityIndicator
    }
  }
}

答案 2 :(得分:0)

这是我加载图片的方式

if(activityList.banner != ""){
    dispatch_async(dispatch_get_global_queue(QOS_CLASS_BACKGROUND, 0), {
    let fileManager = NSFileManager.defaultManager()

    let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
    let pathSplit = activityList.banner.characters.split{$0 == "/"}.map(String.init)
    let getImagePath = (paths as NSString).stringByAppendingPathComponent("\(pathSplit[pathSplit.count-1])")
    if (fileManager.fileExistsAtPath(getImagePath)){ // if I already download the image before I opened from the folder
        func display_image2(){
            activityImageView.image = UIImage(contentsOfFile: getImagePath)
            activityImageView.image = activityImageView.image?.alpha(0.7)
            activityIndicator.hidden = true
            //iconImageView.hidden = true
        }
        dispatch_async(dispatch_get_main_queue(), display_image2)
    }else{ //in another case I download the image from server
        let url:String = "\(Constants().mainURL)/imagecache/activity_preview/" + activityList.banner
        let imgURL: NSURL = NSURL(string: url)!
        let request: NSURLRequest = NSURLRequest(URL: imgURL)

        let session = NSURLSession.sharedSession()
        let task = session.dataTaskWithRequest(request){
            (data, response, error) -> Void in

            if (error == nil && data != nil){
                func display_image(){
                    activityImageView.image = UIImage(data: data!)

                    if let data = UIImageJPEGRepresentation(UIImage(data: data!)!, 0.8) {
                        data.writeToFile(getImagePath, atomically: true)
                    }
                        activityIndicator.hidden = true
                    //iconImageView.hidden = true
                    activityImageView.image = activityImageView.image?.alpha(0.7)

                }
                dispatch_async(dispatch_get_main_queue(), display_image)
            }

        }

        task.resume()
    }
    })
}

答案 3 :(得分:0)

这是@Idindu的答案的改进,因为我使用了他的答案,发现activityIndicator存在一些问题。

主要问题是activityIndicator不会停止,即使图像已经显示,我也被搜索到,发现这是因为任何时候调用它,都会得到一个全新的实例,这就是{ {1}}无效。

接下来的事情是activityIndicator.stopAnimating()的位置并不总是位于activityIndicator的中心,我找到了一种更好的方法here

这是我使用的最终版本:

imageView