Last active
February 29, 2020 02:01
-
-
Save hfossli/f18813f92575c97f52ff4701f34b498d to your computer and use it in GitHub Desktop.
AppVersion
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class AppDelegate: UIResponder, UIApplicationDelegate { | |
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { | |
AppVersion.activateAndSaveCurrentVersion() | |
application.onFirstLaunch { | |
showWelcomeMessage() | |
} | |
application.onUpgrade { (previousVersion, currentVersion) in | |
migrateData(from: previousVersion, to: currentVersion) | |
} | |
return true | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class AppVersion { | |
/* | |
Call this function in AppDelegate | |
*/ | |
static func activateAndSaveCurrentVersion() { | |
// getting these static variables initiliazes them and persists their value to UserDefaults | |
let _ = build | |
let _ = version | |
let _ = full | |
} | |
static let build = AppVersion(infoDictionaryKey: "CFBundleVersion") | |
static let version = AppVersion(infoDictionaryKey: "CFBundleShortVersionString") | |
static let full = AppVersion(combine: version, with: build) | |
let previous: String? | |
let current: String | |
private init(infoDictionaryKey: String) { | |
let key = "\(AppVersion.self).\(infoDictionaryKey).previous" | |
current = Bundle.main.object(forInfoDictionaryKey: infoDictionaryKey) as! String | |
previous = UserDefaults.standard.string(forKey: key) | |
UserDefaults.standard.set(current, forKey: key) | |
} | |
private init(combine a: AppVersion, with b: AppVersion) { | |
if let prevA = a.previous, let prevB = b.previous { | |
previous = "\(prevA).\(prevB)" | |
} else { | |
previous = nil | |
} | |
current = "\(a.current).\(b.current)" | |
} | |
} | |
extension UIApplication { | |
var isFirstLaunch: Bool { | |
return AppVersion.full.previous == nil | |
} | |
var isUpgrade: Bool { | |
if let previous = AppVersion.full.previous, previous != AppVersion.full.current { | |
return true | |
} | |
return false | |
} | |
func onFirstLaunch(_ block: @escaping () -> ()) { | |
if self.isFirstLaunch { | |
block() | |
} | |
} | |
func onUpgrade(_ block: @escaping ((previous: String, current: String)) -> ()) { | |
if self.isUpgrade { | |
block(previous: previous, current: AppVersion.full.current) | |
} | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment