Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

More expiry options (Hours, Days, Months, Years) #42

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 30 additions & 2 deletions AwesomeCache/Cache.swift
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,13 @@ import Foundation
/// Represents the expiry of a cached object
public enum CacheExpiry {
case Never
case Seconds(NSTimeInterval)
case Date(NSDate)
case Seconds(NSTimeInterval)
case Minutes(Int)
case Hours(Int)
case Days(Int)
case Months(Int)
case Years(Int)
}

/// A generic cache that persists objects to disk and is backed by a NSCache.
Expand Down Expand Up @@ -250,14 +255,37 @@ public class Cache<T: NSCoding> {
}

private func expiryDateForCacheExpiry(expiry: CacheExpiry) -> NSDate {
let now = NSDate()

switch expiry {
case .Never:
return NSDate.distantFuture()
case .Seconds(let seconds):
return NSDate().dateByAddingTimeInterval(seconds)
return now.dateByAddingTimeInterval(seconds)
case .Date(let date):
return date
default:
break
}

let offsetComponents = NSDateComponents()

switch expiry {
case .Hours(let hours):
offsetComponents.hour = hours
case .Days(let days):
offsetComponents.day = days
case .Months(let months):
offsetComponents.month = months
case .Years(let years):
offsetComponents.year = years
default:
offsetComponents.hour = 2
}

let cal = NSCalendar.currentCalendar()

return cal.dateByAddingComponents(offsetComponents, toDate: now, options: NSCalendarOptions(rawValue: 0)) ?? now
}

}
1 change: 1 addition & 0 deletions Example.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,7 @@
4D44D2881971627700EC5FDB /* Products */,
);
sourceTree = "<group>";
usesTabs = 1;
};
4D44D2881971627700EC5FDB /* Products */ = {
isa = PBXGroup;
Expand Down