2017-04-12 137 views
2

在函數中實現此流程圖的最佳和最簡單的方法是什麼? 現在我正在使用兩個派遣組,但我需要檢查他們是否都完成了,而不僅僅是當他們完成時。如何檢查兩個異步任務是否成功完成

如果他們這樣做,那麼:

  • 朋友陣列將擁有元素
  • 暱稱陣列將擁有元素

Flowchart

注:FB是Facebook和FIR是火力地堡數據庫

+0

也許你可以嘗試在GCD中的dispatch_barrier_async或dispatch_group。 – Coollee

回答

2

你可以使用DispatchGroup。嘗試下面的操場;

import UIKit 
import XCPlayground 

let dispatchGroup = DispatchGroup.init() 

for index in 0...4 { 
    dispatchGroup.enter() 
    let random = drand48() 
    let deadline = DispatchTime.now() + random/1000 
    print("entered \(index)") 
    DispatchQueue.global(qos: .background).asyncAfter(deadline: deadline, execute: { 
     print("leaving \(index)") 
     dispatchGroup.leave() 
    }) 
} 

dispatchGroup.notify(queue: .global()) { 
    print("finished all") 
}

應該類似於

entered 0 
leaving 0 
entered 1 
entered 2 
leaving 1 
leaving 2 
entered 3 
leaving 3 
entered 4 
leaving 4 
finished all 
+0

因此,如果我然後說,當索引== 0時,我執行Facebook,並且當索引== 1時,我執行Firebase? 從你給出的例子來看,我不需要隨機的,對嗎? –

+0

不,這個想法是說明在開始每個異步任務時將其添加到組中,並在完成時離開。隨機的要點是引入不同的執行時間,並顯示只有在所有異步任務都離開組後纔會調用通知 –

+0

謝謝。您的答案不僅解決了我的問題,而且還清理了我的代碼! –

0

輸出東西,你可以實現斯威夫特3一樣,這個流程圖。

let fbFriendsArray : [String] = [] 
let firNickNames :: [String] = [] 

func flowChart() { 

let myGroupOuter = DispatchGroup() 
myGroupOuter.enter() 

fetchFBfriends(completionHandler: {(isSuccess : Bool) in 

    myGroupOuter.leave() 
}) 

myGroupOuter.enter() 

fetchFIRNickNames(completionHandler: {(isSuccess : Bool) in 

    myGroupOuter.leave() 
}) 

myGroupOuter.notify(queue: DispatchQueue.main) { 

if (fbFriendsArray.isEmpty || firNickNames.isEmpty) { 

    /// Present Your Error Logic 
} else { 

    /// Fetch Games Logic here 
} 

} 

} 

fetchFBfriendsfetchFIRNickNames是負責獲得來自Facebook和火力地堡數據的功能。