在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
1 实现原理(1)我们会发现许多 App 在一次启动时会显示一个新手引导页(下次启动就不会再显示)
(2)其判断原理就是在 AppDelegate 里的 didFinishLaunchingWithOptions 方法中检查 UserDefaults 中是否存在特定的键值:
(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 } }
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) { } }
|
请发表评论