在多个异步方法之后执行代码

时间:2018-05-19 02:58:44

标签: ios swift asynchronous grand-central-dispatch

让我们说我得到了一些类实例的Int数组和数组

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

对于ID数组中的每个项目,我想运行async函数来从服务器请求项目

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

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

2 个答案:

答案 0 :(得分: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)
    }
}

答案 1 :(得分:0)

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

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)
}