swift 如何检查两个异步任务是否成功完成

wfauudbj  于 2023-03-11  发布在  Swift
关注(0)|答案(3)|浏览(151)

在函数中实现这个流程图的最好和最简单的方法是什么?现在我使用两个调度组,但是我需要检查它们是否都完成了,而不仅仅是当它们完成的时候。
如果完成,则:

  • friends数组将包含元素
  • nicknames数组将包含元素

注:FB是Facebook,FIR是Firebase数据库

mkshixfv

mkshixfv1#

您可以使用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
igsr9ssn

igsr9ssn2#

Swift 5 +异步等待

让我们想象一下,你想加载3个图像在同一时间,并等待他们下载到目前在屏幕上。

Task {
    do {
        // Call first function and proceed to next step
        async let image_1 = try firstAsyncMethod()
        
        // Call second function and proceed to next step
        async let image_2 = try secondAsyncMethod()
        
        // Call function and proceed to next step
        async let image_3 = try thirdAsyncMethod()
        
        let images = try await [image_1, image_2, image_3]
        // Display images
        
    } catch {
        // Handle Error
    }
}
0kjbasz6

0kjbasz63#

您可以像这样在Swift 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和Firebase获取数据的函数。

相关问题