Accueil

Afficher un ViewController au premier lancement uniquement

Tutoriel Swift

Posté par Véronique le 10 March 2020

Il n'est pas rare de vouloir afficher un écran en particulier lors du premier lancement d'une application mobile. C'était mon cas, et voilà comment j'ai procédé :

1. Le Soryboard

Dans le fichier Main.storyboard j'ai défini 2 ViewController :

screenshot
  • Le premier Start View Controller correspond à l'écran que je souhaite afficher lors du premier lancement. Je lui ai attribué l'identifiant StartViewControllerID.
  • Le second Home View Controller sera mon premier écran lors de tous les autres lancements de l'application. Son identifiant est HomeViewControllerID.

2. Le Code

Dans le fichier SceneDelegate.swift, on va sauvegarder un booléen nous indiquant que le premier lancement de l'application a déjà eu lieu. Nous allons, à chaque lancement, récupérer ce booléen pour définir le comportement a adopter. Bien sur, lors du premier lancement, ce booléen n'existera pas et sa valeur sera donc false.

// SceneDelegate.swift

import UIKit

class SceneDelegate: UIResponder, UIWindowSceneDelegate {

    var window: UIWindow?

    func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
        // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
        // If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
        // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
        guard let _ = (scene as? UIWindowScene) else { return }

        let firstLaunchOccurred = UserDefaults.standard.bool(forKey: "FirstLaunchOccurred")
        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        if firstLaunchOccurred  {
            // Show the HomeViewController 
            self.window?.rootViewController = storyboard.instantiateViewController(withIdentifier: "HomeViewControllerID")

        } else {
            // Show StartViewController only on first launch
            self.window?.rootViewController = storyboard.instantiateViewController(withIdentifier: "StartViewControllerID")
            UserDefaults.standard.set(true, forKey: "FirstLaunchOccurred")
        }
    }
    ...        
}