-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTimeoutObserver.swift
More file actions
56 lines (43 loc) · 1.56 KB
/
TimeoutObserver.swift
File metadata and controls
56 lines (43 loc) · 1.56 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
/*
Copyright (C) 2015 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
This file shows how to implement the OperationObserver protocol.
*/
import Foundation
/**
`TimeoutObserver` is a way to make an `Operation` automatically time out and
cancel after a specified time interval.
*/
struct TimeoutObserver: OperationObserver {
// MARK: Properties
static let timeoutKey = "Timeout"
private let timeout: NSTimeInterval
// MARK: Initialization
init(timeout: NSTimeInterval) {
self.timeout = timeout
}
// MARK: OperationObserver
func operationDidStart(operation: Operation) {
// When the operation starts, queue up a block to cause it to time out.
let when = dispatch_time(DISPATCH_TIME_NOW, Int64(timeout * Double(NSEC_PER_SEC)))
dispatch_after(when, dispatch_get_global_queue(QOS_CLASS_DEFAULT, 0)) {
/*
Cancel the operation if it hasn't finished and hasn't already
been cancelled.
*/
if !operation.finished && !operation.cancelled {
let error = NSError(code: .ExecutionFailed, userInfo: [
self.dynamicType.timeoutKey: self.timeout
])
operation.cancelWithError(error)
}
}
}
func operation(operation: Operation, didProduceOperation newOperation: NSOperation) {
// No op.
}
func operationDidFinish(operation: Operation, errors: [NSError]) {
// No op.
}
}