@@ -12,15 +12,22 @@ public struct SupabaseLogConfig: Hashable {
12
12
let supabaseAnonKey : String
13
13
14
14
let table : String
15
+ let isDebug : Bool
15
16
16
17
public init (
17
18
supabaseURL: String ,
18
19
supabaseAnonKey: String ,
19
- table: String = " logs "
20
+ table: String = " logs " ,
21
+ isDebug: Bool = true
20
22
) {
21
23
self . supabaseURL = supabaseURL
22
24
self . supabaseAnonKey = supabaseAnonKey
23
25
self . table = table
26
+ #if DEBUG
27
+ self . isDebug = isDebug
28
+ #else
29
+ self . isDebug = false
30
+ #endif
24
31
}
25
32
}
26
33
@@ -68,6 +75,9 @@ final class SupabaseLogManager {
68
75
let cache : LogsCache
69
76
let config : SupabaseLogConfig
70
77
78
+ private let minimumWaitTimeBetweenRequests : TimeInterval = 10
79
+ private var sendTimer : Timer ?
80
+
71
81
private static let queue = DispatchQueue (
72
82
label: " co.binaryscraping.supabase-log-manager.instances " )
73
83
private static var instances : [ SupabaseLogConfig : SupabaseLogManager ] = [ : ]
@@ -103,15 +113,29 @@ final class SupabaseLogManager {
103
113
name: UIApplication . didEnterBackgroundNotification, object: nil )
104
114
}
105
115
#endif
116
+
117
+ startTimer ( )
118
+ }
119
+
120
+ private func startTimer( ) {
121
+ sendTimer? . invalidate ( )
122
+ sendTimer = Timer . scheduledTimer (
123
+ timeInterval: minimumWaitTimeBetweenRequests, target: self ,
124
+ selector: #selector( checkForLogsAndSend) , userInfo: nil , repeats: true )
125
+
126
+ // Fire the timer to attempt to send any cached logs from a previous session.
127
+ checkForLogsAndSend ( )
106
128
}
107
129
108
130
func log( _ payload: [ String : Any ] ) {
109
131
cache. push ( payload)
110
132
}
111
133
134
+ @objc
112
135
private func checkForLogsAndSend( ) {
113
136
let logs = cache. pop ( )
114
- if logs. isEmpty { return }
137
+
138
+ guard !logs. isEmpty else { return }
115
139
116
140
let data = try ! JSONSerialization . data ( withJSONObject: logs)
117
141
guard
@@ -142,7 +166,11 @@ final class SupabaseLogManager {
142
166
throw URLError ( . badServerResponse)
143
167
}
144
168
} catch {
145
- print ( error)
169
+ if self . config. isDebug {
170
+ print ( error)
171
+ }
172
+
173
+ // An error ocurred, put logs back in cache.
146
174
self . cache. push ( logs)
147
175
}
148
176
}
@@ -152,14 +180,30 @@ final class SupabaseLogManager {
152
180
153
181
extension SupabaseLogManager {
154
182
@objc func appWillTerminate( ) {
183
+ if config. isDebug {
184
+ print ( #function)
185
+ }
186
+
155
187
cache. backupCache ( )
156
188
}
157
189
158
190
#if os(iOS)
159
191
@objc func didEnterForeground( ) {
192
+ if config. isDebug {
193
+ print ( #function)
194
+ }
195
+
196
+ startTimer ( )
160
197
}
161
198
162
199
@objc func didEnterBackground( ) {
200
+ if config. isDebug {
201
+ print ( #function)
202
+ }
203
+
204
+ sendTimer? . invalidate ( )
205
+ sendTimer = nil
206
+
163
207
cache. backupCache ( )
164
208
}
165
209
#endif
0 commit comments