2

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

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{ $0.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()
  }
})

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

4

1 回答 1

6

我相信你需要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{ $0.filePath }
    }

    completion()
  }
于 2017-03-10T18:10:45.250 回答