How to check if two asynchronous tasks are done with success

谁说胖子不能爱 提交于 2019-12-12 09:17:48

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!