Skip to content

Instantly share code, notes, and snippets.

@dqhieu
Created September 6, 2016 07:30
Show Gist options
  • Save dqhieu/fe7f0c3b924f03082027f83a21df7f2e to your computer and use it in GitHub Desktop.
Save dqhieu/fe7f0c3b924f03082027f83a21df7f2e to your computer and use it in GitHub Desktop.
class TimeOut: NSObject {
private let queue:dispatch_queue_t
private let semaphore:dispatch_semaphore_t
var completion:()->()
convenience init(_ seconds:Double, completion:()->()) {
self.init(seconds, fireOn:dispatch_get_main_queue(), completion:completion)
}
required init(_ seconds:Double, fireOn:dispatch_queue_t, completion:()->()) {
self.semaphore = dispatch_semaphore_create(0)
self.queue = dispatch_queue_create("timeout", nil)
self.completion = completion
super.init()
dispatch_async(queue) {
let timeoutTime = dispatch_time(DISPATCH_TIME_NOW, Int64(seconds * Double(NSEC_PER_SEC)));
let result = dispatch_semaphore_wait(self.semaphore, timeoutTime)
dispatch_async(fireOn) {
if result != 0 {
self.completion()
}
}
}
}
func satisfy() {
dispatch_semaphore_signal(semaphore)
}
}
// Usage
var timeout: TimeOut?
func startTimeout() {
timeout = TimeOut(5.0) {
[weak self] in
self?.gotoNext()
}
}
@IBAction func tapAnywhere(sender: AnyObject) {
timeout?.satisfy()
gotoNext()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment