Reputation: 2100
I have an app that preloads a CSV file into Core Data when the app is launched for the first time like so:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
let isPreloaded = defaults.bool(forKey: "isPreloaded")
if !isPreloaded {
preloadData()
defaults.set(true, forKey: "isPreloaded")
}
}
However, I want to preload a new updated CSV file when the app is updated. I suppose I could create a new key called "isPreloaded2" in my defaults, but the CSV file is going to change with every update and I was wondering if there's a better way.
Upvotes: 0
Views: 370
Reputation: 2100
Thanks to JoRa for his solution. For anyone who's interested, here's how I implemented it in Swift:
Swift 3.0
let defaults = UserDefaults.standard
if let version = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String {
let currentVersion = defaults.value(forKey: "currentVersion") as? String
if version != currentVersion { //currentVersion will either be nil or last version number when app is launched after update.
preloadData()
defaults.set(version, forKey: "currentVersion") //update currentVersion in defaults so version will match currentVersion next time.
}
}
And don't forget to remove old data before you preload new data as well (my preloadData() function includes a removeData() function).
Upvotes: 1
Reputation: 3877
Maybe you could create a key lastUpdatedVersion
in the userDefaults for checking which version has already been updated.
Then you can check something like:
let currentVersion = Bundle.main.infoDictionary?["CFBundleShortVersionString"]
if !NSUserDefaults.standardUserDefaults.objectForKey(key: "lastVersionUpdated") || NSUserDefaults.standardUserDefaults.objectForKey(key: "lastVersionUpdated") != currentVersion
{
//Update your CSV here
//...
NSUserDefaults.standardUserDefaults.setObjectForKey(key: "lastVersionUpdated", object: currentVersion)
}
But it's still up to you to decide, whether this is an elegant solution or not.
Upvotes: 0