Skip to content

Instantly share code, notes, and snippets.

@shu223
Last active October 12, 2017 08:07
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shu223/e7e4ab419d1e53061249 to your computer and use it in GitHub Desktop.
Save shu223/e7e4ab419d1e53061249 to your computer and use it in GitHub Desktop.
// Modified from: https://github.com/katleta3000/CancelBlocks/blob/master/CancelBlocks.swift
typealias dispatch_cancelable_block_t = (cancel: Bool) -> (Void)
private func dispatch_after_delay(delay: Double, queue: dispatch_queue_t, block: dispatch_block_t?) -> dispatch_cancelable_block_t? {
guard let block = block else { return nil }
var originalBlock: dispatch_block_t? = block
var cancelableBlock: dispatch_cancelable_block_t? = nil
let delayBlock: dispatch_cancelable_block_t = {(cancel: Bool) -> Void in
if let originalBlock = originalBlock where !cancel {
dispatch_async(queue, originalBlock)
}
cancelableBlock = nil
originalBlock = nil
}
cancelableBlock = delayBlock
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(delay * Double(NSEC_PER_SEC))), queue) { () -> Void in
if let cancelableBlock = cancelableBlock {
cancelableBlock(cancel: false)
}
}
return cancelableBlock
}
func dispatch_after_delay(delay: Double, block: dispatch_block_t?) -> dispatch_cancelable_block_t? {
let queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
return dispatch_after_delay(delay, queue: queue, block: block)
}
func dispatch_on_main_queue_after_delay(delay: Double, block: dispatch_block_t?) -> dispatch_cancelable_block_t? {
return dispatch_after_delay(delay, queue: dispatch_get_main_queue(), block: block)
}
func cancel_block(block: dispatch_cancelable_block_t?) {
if let block = block {
block(cancel: true)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment