ios - 等到 Boolean 在 Swift 中为真?

标签 ios swift xcode

我有一些单元格带有按钮,可以触发从网上下载各自的 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/

相关文章:

ios - 动态类型静态 UITableViewCell

iphone - PushViewController 不适用于 Reveal Controller

ios - 当 Apple 从设置中删除 Twitter 时,如何在 Xcode 9 Simulator 中访问它?

swift - iOS swift 深层链接 https ://or http://schema

ios - Xcode 6 : Create init function automatically?

ios - 架构 armv7 的 undefined symbol : "_objc_readClassPair", 引用自 : __ARCLite__load() in libarclite_iphoneos. a(arclite.o)

iPhone兼容性

ios - Xcode 使用 cocoapods 框架找到具有相同标识符的包

ios - 将 Swift 函数转换为 Objective C 并在 swift 中使用返回值

swift - 自定义协议(protocol)