问题
What is the best and easiest way to implement this flowchart in a function? Right now I'm using two dispatch groups but I need to check if they're both done, and not only when they finish.
If they are done then:
- friends array will have elements
- nicknames array will have elements
note: FB is Facebook and FIR is Firebase database
回答1:
You could do this using DispatchGroup. Try the following playground;
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")
}
which should output something similar to
entered 0 leaving 0 entered 1 entered 2 leaving 1 leaving 2 entered 3 leaving 3 entered 4 leaving 4 finished all
回答2:
You can implement this flow chart in Swift 3 like that.
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
}
}
}
fetchFBfriends and fetchFIRNickNames are functions that are responsible to get the data from Facebook and Firebase.
来源:https://stackoverflow.com/questions/43362989/how-to-check-if-two-asynchronous-tasks-are-done-with-success