【问题标题】:Do something when all alamofire requests are finished当所有 alamofire 请求完成时做一些事情
【发布时间】:2017-04-03 15:33:50
【问题描述】:

我有一个 url 数组,我想为该数组中的每个 url 发出一个 alamofire 请求:

func getData(completion: @scaping(_success: Bool) -> Void) {
  for url in self.myArray {
     Alamofire.request(url).responseImage { response in
        if let image = response.result.value {
          print(image)
          completion(true)
        }
     }
  }
}

问题是我不知道所有请求何时完成,可能是因为for 循环。即使使用完成处理程序。 如果我尝试在 getData 成功时执行某些操作,则某些请求尚未完成。

我想在所有请求完成后做一些事情,比如更新一个 tableView

【问题讨论】:

  • 查看调度组...
  • 我想这正是我想要的,谢谢

标签: swift request alamofire


【解决方案1】:

如果你知道你有多少个 url(你知道),只需记录你到达完成处理程序的频率 - 像这样。

func getData(completion: @scaping(_success: Bool) -> Void) {
    var urlCounter = self.myArray.count
    for url in self.myArray {
        Alamofire.request(url).responseImage { response in
            if let image = response.result.value {
                print(image)
                completion(true)
                urlCounter -= 1
                if urlCounter == 0
                {
                    // everything finished - do completion stuff
                }
            }
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-12-31
    • 1970-01-01
    • 1970-01-01
    • 2021-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多