【问题标题】:Execute code after number of async methods [duplicate]在异步方法数量之后执行代码[重复]
【发布时间】:2018-05-19 02:58:43
【问题描述】:

假设我得到了一些类实例的 Int 数组和数组

var IDs = [Int]()
var items = [Item]()

对于 IDs 数组中的每个项目,我想运行异步函数以从服务器请求项目

for id in IDs {
    let item = requestItem(id)
    items.append(item)
}

由于 requestItem 以异步方式工作 - 如何仅在加载所有项目后执行代码?

【问题讨论】:

    标签: ios swift asynchronous grand-central-dispatch


    【解决方案1】:
    func requestItem(id: Int, completion: @escaping (Item) -> ()) {
        DispatchQueue.global(qos: .background).async {
            let item = Item()
            completion(item)
        }              
    }
    
    var IDs = [Int]()
    var items = [Item]()
    
    for id in IDs {
        requestItem(id: id) { (derivedItem) in
            items.append(derivedItem)
        }
    }
    

    【讨论】:

    • 如何在所有异步调用都完成后才执行代码?
    • @moonvader,我对requestItem() 进行了编辑以帮助澄清。基本上,一旦您获得了 item 的值,您将在 requestItem 的异步队列中调用您的完成
    • 假设我需要并行运行此函数 100 次,并且我需要知道何时完成所有 100 个函数调用。我认为解决方案是使用 DispatchGroups
    • @moonvader 如果您正在等待 100 个呼叫完成,那么调度组就是要走的路
    【解决方案2】:

    您必须为发出服务器请求的函数使用完成块,并且需要应用更多逻辑来向用户显示正在发生的事情。

    var IDs = [Int]()
    var items = [Item]()
    
    for id in IDs {
        requestItem(itemId : id, finished : { (objItem : Item) -> Void in
           items.append(objItem)
           // Below condition is to check weather all async service call response are came then hide loader or show items to user, etc. whatever you want to do after get all calls responses  
           if IDs.count == items.count {
               // Show item to user or perform your further operation
           }
        })
    }
    

    有完成块的函数

    func requestItem(itemId : Int, finished: (objItem : Item) -> Void) {
    
         print("Item details fetched!")
    
         // Store your response in your Item class object and pass it like below
         let objItem = Item()  // You constructor or any other logic to store value in objItem 
    
         // Call finished when you have data initialized in your objItem object
         finished(objItem)
    }
    

    【讨论】:

      猜你喜欢
      • 2018-07-26
      • 1970-01-01
      • 2020-06-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-25
      • 1970-01-01
      相关资源
      最近更新 更多