Skip to content

Commit

Permalink
Merge pull request #44 from RocketCommunicationsInc/cache-improvements
Browse files Browse the repository at this point in the history
Cache improvements
  • Loading branch information
rocketjeff authored Jul 7, 2023
2 parents a4d71f5 + 26320e3 commit a5a00f0
Showing 1 changed file with 26 additions and 6 deletions.
32 changes: 26 additions & 6 deletions Shared/Data/NetworkManager.swift
Original file line number Diff line number Diff line change
Expand Up @@ -106,17 +106,32 @@ class NetworkManager:ObservableObject
// Convert into an array of Launch objects
private func loadLaunches(_ timePeriod:TimePeriod) async
{
// if the cached data is usable process that data, otherwise download new data
if cacheIsUsable(timePeriod){
if launchesEmpty(timePeriod) // no need to reload existing cached data
// if no data is available, probably startup or first run
if launchesEmpty(timePeriod)
{
// if ANY cache is available, even if old
if cacheIsAvailable(timePeriod)
{
// load the cache, even if old
loadFromCache(timePeriod)
}
}
else {

// check if cache is old, begin to load from network
if !cacheIsUsable(timePeriod)
{
await loadFromNetwork(timePeriod)
}
}

// return true if there is some data in the cache
func cacheIsAvailable(_ timePeriod:TimePeriod)->Bool {

let cacheSize = timePeriod == .upcoming ? upcomingDataCache.count : recentDataCache.count

return cacheSize > 1
}


// return true if the cache for timePeriod is less than refreshInterval minutes old, and there is some data in the cache
func cacheIsUsable(_ timePeriod:TimePeriod)->Bool {
Expand All @@ -129,7 +144,6 @@ class NetworkManager:ObservableObject

// load from cached data for timePeriod
func loadFromCache(_ timePeriod:TimePeriod) {
print("good cache found")
let data = timePeriod == .upcoming ? upcomingDataCache : recentDataCache
let myLaunches = try! JSONDecoder().decode(LaunchReplies.self, from: data)

Expand Down Expand Up @@ -164,7 +178,13 @@ class NetworkManager:ObservableObject
guard (200...299).contains(status) else {
if (status == 429) {
// handle "Too Many Requests" error
self.prepareAlert(title: "Too Many Requests", message: HTTPURLResponse.localizedString(forStatusCode: status))
// Do not show an alert for this error. Because launches uses the free version
// of the API, this error can rise often with multiple users on the same IP address.
// Instead, just fail silently, hopefully displaying some cached data.
// A better solution would be to show a small note somewhere in the display
// indicating that the data is stale.
// Even better, paying for API access.
//self.prepareAlert(title: "Too Many Requests", message: HTTPURLResponse.localizedString(forStatusCode: status))
}
else {
// handle generic error
Expand Down

0 comments on commit a5a00f0

Please sign in to comment.