Last active
October 12, 2017 08:07
-
-
Save shu223/e7e4ab419d1e53061249 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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