Skip to content

Commit 2d6958b

Browse files
committed
improvements in the implementation
1 parent 0fbc9a2 commit 2d6958b

File tree

1 file changed

+18
-4
lines changed

1 file changed

+18
-4
lines changed

FlagsmithClient/Classes/Flagsmith.swift

Lines changed: 18 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -228,7 +228,7 @@ public final class Flagsmith: @unchecked Sendable {
228228
let flags = try JSONDecoder().decode([Flag].self, from: cachedResponse.data)
229229
return flags
230230
} catch {
231-
// Cache data is corrupted, return nil
231+
print("Flagsmith - Failed to decode cached flags: \(error.localizedDescription)")
232232
return nil
233233
}
234234
}
@@ -242,7 +242,9 @@ public final class Flagsmith: @unchecked Sendable {
242242

243243
// Create request for identity-specific flags
244244
let identityURL = baseURL.appendingPathComponent("identities/")
245-
var components = URLComponents(url: identityURL, resolvingAgainstBaseURL: false)!
245+
guard var components = URLComponents(url: identityURL, resolvingAgainstBaseURL: false) else {
246+
return nil
247+
}
246248
components.queryItems = [URLQueryItem(name: "identifier", value: identity)]
247249

248250
guard let url = components.url else { return nil }
@@ -256,7 +258,7 @@ public final class Flagsmith: @unchecked Sendable {
256258
let identity = try JSONDecoder().decode(Identity.self, from: cachedResponse.data)
257259
return identity.flags
258260
} catch {
259-
// Cache data is corrupted, return nil
261+
print("Flagsmith - Failed to decode cached identity flags: \(error.localizedDescription)")
260262
return nil
261263
}
262264
}
@@ -285,8 +287,20 @@ public final class Flagsmith: @unchecked Sendable {
285287
}
286288
}
287289

288-
// If no cache control, assume valid for the configured TTL
290+
// If no cache control, validate against configured TTL
291+
if cacheConfig.cacheTTL > 0 {
292+
if let dateString = httpResponse.allHeaderFields["Date"] as? String,
293+
let date = HTTPURLResponse.dateFormatter.date(from: dateString) {
294+
let age = Date().timeIntervalSince(date)
295+
return age < cacheConfig.cacheTTL
296+
}
297+
// No Date header, be conservative
298+
return false
299+
}
300+
// TTL of 0 means infinite
301+
289302
return true
303+
290304
}
291305

292306
private func extractMaxAge(from cacheControl: String) -> TimeInterval? {

0 commit comments

Comments
 (0)