永远不会调用完成块?

Completion block never gets called?

我们有一个函数,当它完成时,应该在它的完成块中调用另一个函数,但永远不会调用完成块中的任何内容。这是函数:

func appendAllData (completion: () -> Void) {

    guard let movieDetails = self.movieDetailsData else {
      // handle nil case
      return;
    }

    if let posterImage = self.movieDetailsData?.poster {
      self.posterArray.append(posterImage)
    }

    if let overview = self.movieDetailsData?.overview {
      self.overviewArray.append(overview)
    }

    if let releaseDate = self.movieDetailsData?.releaseData {
      self.releaseInfoArray.append(releaseDate)
    }

    if let runtime = self.movieDetailsData?.runtime {
      self.releaseInfoArray.append(String(describing: runtime))
    }

    if let genre = self.movieDetailsData?.genre {
      if !genre.isEmpty {
        self.releaseInfoArray.append(genre[0].name)
      }
    }

    if let budget = self.movieDetailsData?.budget {
      self.boxOfficeArray.append(budget)
    }

    if let revenue = self.movieDetailsData?.revenue {
      self.boxOfficeArray.append(revenue)
    }

    if let homepage = self.movieDetailsData?.homepage {
      self.homePageArray.append(homepage)
    }

    if let images = self.movieDetailsData?.images {
      self.imageArray += images.backdropImages.map{ [=10=].filePath }
    }
  }

使用方法如下:

self.appendAllData(completion: { _ in
//Nothing inside here gets called
  DispatchQueue.main.async {

    print(self.movieDetailsData?.poster )

    if let bgImage = self.movieDetailsData?.poster {
      self.backgroundImage.sd_setImage(with: URL(string:"\(baseImageURL)\(bgImage)"))
      print("background pic loaded")
      self.backgroundImage.addBlurEffect()
    }

    self.detailTableView.reloadData()
  }
})

完成块中没有任何内容被调用,知道如何解决这个问题吗?

我相信你需要在最后调用 completion() 来执行你的完成代码。

func appendAllData (completion: () -> Void) {

    guard let movieDetails = self.movieDetailsData else {
      // handle nil case
      return;
    }

    if let posterImage = self.movieDetailsData?.poster {
      self.posterArray.append(posterImage)
    }

    if let overview = self.movieDetailsData?.overview {
      self.overviewArray.append(overview)
    }

    if let releaseDate = self.movieDetailsData?.releaseData {
      self.releaseInfoArray.append(releaseDate)
    }

    if let runtime = self.movieDetailsData?.runtime {
      self.releaseInfoArray.append(String(describing: runtime))
    }

    if let genre = self.movieDetailsData?.genre {
      if !genre.isEmpty {
        self.releaseInfoArray.append(genre[0].name)
      }
    }

    if let budget = self.movieDetailsData?.budget {
      self.boxOfficeArray.append(budget)
    }

    if let revenue = self.movieDetailsData?.revenue {
      self.boxOfficeArray.append(revenue)
    }

    if let homepage = self.movieDetailsData?.homepage {
      self.homePageArray.append(homepage)
    }

    if let images = self.movieDetailsData?.images {
      self.imageArray += images.backdropImages.map{ [=10=].filePath }
    }

    completion()
  }