Swift - 判断应用是否是第一次启动(或当前版本是否第一次启动)
作者:hangge | 2018-06-01 08:10
1,实现原理
(1)我们会发现许多 App 在一次启动时会显示一个新手引导页(下次启动就不会再显示),这个我之前也写过相关的文章:
(2)其判断原理就是在 AppDelegate 里的 didFinishLaunchingWithOptions 方法中检查 UserDefaults 中是否存在特定的键值:
- 不存在则说明是第一次运行,我们便把根视图控制器改成引导页,并保存这个特定的键值(Bool 类型即可)。
- 已存在则说明之前已运行过该应用,那么就显示默认视图。
(3)有时我们还想在应用更新后,新版本第一次启动时显示个新功能说明页,其原理同样是判断 UserDefaults 里的键值。只不过这次保存的是版本号,每次将之前保存的版本号与当前应用的版本号做比较:
- 不同则说明新版本第一次启动。
- 相同则说明新版本之前已经启动过。
2,样例代码
(1)为方便使用,这里对 UserDefaults 进行扩展,增加两个判断是否是第一次启动的方法:
extension UserDefaults {
//应用第一次启动
static func isFirstLaunch() -> Bool {
let hasBeenLaunched = "hasBeenLaunched"
let isFirstLaunch = !UserDefaults.standard.bool(forKey: hasBeenLaunched)
if isFirstLaunch {
UserDefaults.standard.set(true, forKey: hasBeenLaunched)
UserDefaults.standard.synchronize()
}
return isFirstLaunch
}
//当前版本第一次启动
static func isFirstLaunchOfNewVersion() -> Bool {
//主程序版本号
let infoDictionary = Bundle.main.infoDictionary!
let majorVersion = infoDictionary["CFBundleShortVersionString"] as! String
//上次启动的版本号
let hasBeenLaunchedOfNewVersion = "hasBeenLaunchedOfNewVersion"
let lastLaunchVersion = UserDefaults.standard.string(forKey:
hasBeenLaunchedOfNewVersion)
//版本号比较
let isFirstLaunchOfNewVersion = majorVersion != lastLaunchVersion
if isFirstLaunchOfNewVersion {
UserDefaults.standard.set(majorVersion, forKey:
hasBeenLaunchedOfNewVersion)
UserDefaults.standard.synchronize()
}
return isFirstLaunchOfNewVersion
}
}
(2)在 AppDelegate.swift 中调用上面的扩展方法进行判断,并执行相应逻辑。
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
//程序启动
func application(_ application: UIApplication, didFinishLaunchingWithOptions
launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
//判断当前版本是否第一次启动
if UserDefaults.isFirstLaunchOfNewVersion() {
//显示新功能介绍页
print("当前版本第一次启动")
let introductionViewController = IntroductionViewController()
self.window!.rootViewController = introductionViewController
}
//判断是否第一次启动(两个都是第一次则以这个为准)
if UserDefaults.isFirstLaunch() {
//显示新手指导页
print("应用第一次启动")
let guideViewController = GuideViewController()
self.window!.rootViewController = guideViewController
}
return true
}
func applicationWillResignActive(_ application: UIApplication) {
}
func applicationDidEnterBackground(_ application: UIApplication) {
}
func applicationWillEnterForeground(_ application: UIApplication) {
}
func applicationDidBecomeActive(_ application: UIApplication) {
}
func applicationWillTerminate(_ application: UIApplication) {
}
}
(3)三种不同的情况下(应用第一次运行、当前版本第一次运行、都不是第一次)启动效果分别如下:
全部评论(0)