gpt4 book ai didi

ios - 等到 Boolean 在 Swift 中为真?

转载 作者:行者123 更新时间:2023-11-28 06:37:54 25 4
gpt4 key购买 nike

我有一些单元格带有按钮,可以触发从网上下载各自的 PDF。我想要它,以便一次只能下载一个,而其他下载(如果单击它们的按钮)等待它完成。

我不能使用任何类型的队列,因为队列操作会调用下载方法但不会等待它们完成后再继续。

有没有什么方法可以让我只能在完成下载功能通过传递 bool 值或其他内容表示已准备就绪后才能继续?我在这里很迷路,所以非常感谢任何方向。

最佳答案

I cannot use any sort of queue, because the queue operation calls the download methods but does not wait for them to complete before moving on.

这可以使用 NSOperation 队列来完成。关键是您的下载任务必须是异步 NSOperation 子类,您在下载完成时将操作标记为已完成。更重要的是,这些操作应该在串行队列中排队。然后,操作将以 FIFO 顺序一次只执行一个。

但是,以这种方式设置 NSOperations 需要一些样板。另一个好方法是使用 Dispatch Groups。

// A serial queue ensures only one operation is executed at a time, FIFO
let downloadsQueue = dispatch_queue_create("com.youapp.pdfdownloadsqueue", DISPATCH_QUEUE_SERIAL)
let downloadGroup = dispatch_group_create()

func queueDownload(from url: NSURL) {
// Register this download task with the group
dispatch_group_enter(downloadGroup)

// Async dispatch the download task to our serial queue,
// so that it returns control back without blocking the main thread
dispatch_async(downloadsQueue) {
downloadPDF(with: url) { (pdf, error) in
// handle PDF data / error
// { .. }

// leave the dispatch group in the completion method,
// notifying the group that this task is finished
dispatch_group_leave(downloadGroup)
}
}
}

func downloadPDF(with url: NSURL, completion: (pdf: NSData?, error: ErrorType?) -> ()) {
// make network request
// call completion with PDF data or error when the download request returns
}

关于ios - 等到 Boolean 在 Swift 中为真?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38670115/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com