13
13
// limitations under the License.
14
14
15
15
import Foundation
16
+ #if os(macOS)
17
+ import Cocoa
18
+ import AppKit
19
+ #elseif os(watchOS)
20
+ import WatchKit
21
+ #endif
16
22
17
23
///
18
24
/// The SessionInitiator is responsible for:
@@ -22,8 +28,73 @@ import Foundation
22
28
/// and comes to the foreground.
23
29
///
24
30
class SessionInitiator {
31
+ let sessionTimeout : TimeInterval = 30 * 60 // 30 minutes
32
+ let currentTime : ( ) -> Date
33
+ var backgroundTime = Date . distantFuture
34
+ var initiateSessionStart : ( ) -> Void = { }
35
+
36
+ init ( currentTimeProvider: @escaping ( ) -> Date = Date . init) {
37
+ currentTime = currentTimeProvider
38
+ }
39
+
25
40
func beginListening( initiateSessionStart: @escaping ( ) -> Void ) {
26
- // Only cold start is implemented right now
27
- initiateSessionStart ( )
41
+ self . initiateSessionStart = initiateSessionStart
42
+ self . initiateSessionStart ( )
43
+
44
+ let notificationCenter = NotificationCenter . default
45
+ #if os(iOS) || os(tvOS)
46
+ notificationCenter. addObserver (
47
+ self ,
48
+ selector: #selector( appBackgrounded) ,
49
+ name: UIApplication . didEnterBackgroundNotification,
50
+ object: nil
51
+ )
52
+ notificationCenter. addObserver (
53
+ self ,
54
+ selector: #selector( appForegrounded) ,
55
+ name: UIApplication . didBecomeActiveNotification,
56
+ object: nil
57
+ )
58
+ #elseif os(macOS)
59
+ notificationCenter. addObserver (
60
+ self ,
61
+ selector: #selector( appBackgrounded) ,
62
+ name: NSApplication . didResignActiveNotification,
63
+ object: nil
64
+ )
65
+ notificationCenter. addObserver (
66
+ self ,
67
+ selector: #selector( appForegrounded) ,
68
+ name: NSApplication . didBecomeActiveNotification,
69
+ object: nil
70
+ )
71
+ #elseif os(watchOS)
72
+ // Versions below WatchOS 7 do not support lifecycle events
73
+ if #available( watchOSApplicationExtension 7 . 0 , * ) {
74
+ notificationCenter. addObserver (
75
+ self ,
76
+ selector: #selector( appBackgrounded) ,
77
+ name: WKExtension . applicationDidEnterBackgroundNotification,
78
+ object: nil
79
+ )
80
+ notificationCenter. addObserver (
81
+ self ,
82
+ selector: #selector( appForegrounded) ,
83
+ name: WKExtension . applicationDidBecomeActiveNotification,
84
+ object: nil
85
+ )
86
+ }
87
+ #endif
88
+ }
89
+
90
+ @objc func appBackgrounded( ) {
91
+ backgroundTime = currentTime ( )
92
+ }
93
+
94
+ @objc func appForegrounded( ) {
95
+ let interval = currentTime ( ) . timeIntervalSince ( backgroundTime)
96
+ if interval > sessionTimeout {
97
+ initiateSessionStart ( )
98
+ }
28
99
}
29
100
}
0 commit comments