Recherche…


Introduction

AppDelegate est un protocole qui définit les méthodes appelées par l'objet singleton UIApplication en réponse à des événements importants survenant pendant la durée de vie d'une application.

Normalement utilisé pour effectuer des tâches au démarrage de l'application (environnement d'application de configuration, analitycs (ex .: Mixpanel / GoogleAnalytics / Crashlitics), pile de base de données, etc.) les tâches.

Tous les états d'application via les méthodes AppDelegate

Pour vous mettre à jour ou faire quelque chose avant que l'application ne soit mise en ligne, vous pouvez utiliser la méthode ci-dessous.

AppDidFinishLaunching

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Write your code before app launch
    return YES;
}

Alors que l'application entre en premier plan:

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}

Lors du lancement de l'application et de l'arrière-plan du premier plan, cliquez sur la méthode ci-dessous:

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

Alors que l'application entre en arrière-plan:

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

Pendant que l'application démissionne active

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}

Alors que l'application se termine:

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

Rôles AppDelegate:

  • AppDelegate contient le startup code votre application.
  • Il répond aux key changes de l' state de votre application. Plus précisément, il répond aux interruptions temporaires et aux modifications de l'état d'exécution de votre application, par exemple lorsque votre application passe du premier plan à l'arrière-plan.
  • Il responds to notifications provenant de l'extérieur de l'application, telles que les notifications à distance (également appelées notifications push), les avertissements de mémoire insuffisante, les notifications de fin de téléchargement, etc.
  • Il determines si state preservation et la restoration state preservation doivent avoir lieu et aide au processus de préservation et de restauration, le cas échéant.
  • Il responds to events qui ciblent l'application elle-même et ne sont pas spécifiques aux vues de votre application ou aux contrôleurs de vue. Vous pouvez l'utiliser pour stocker les objets de données centraux de votre application ou tout contenu ne possédant pas de contrôleur de vue propriétaire.

Ouverture d'une ressource spécifiée par URL

Demande au délégué d'ouvrir une ressource spécifiée par une URL et fournit un dictionnaire des options de lancement.

Exemple d'utilisation:

func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
        return SomeManager.shared.handle(
            url,
            sourceApplication: options[.sourceApplication] as? String,
            annotation: options[.annotation]
        )
    }

Gestion des notifications locales et distantes

Exemple d'utilisation:

/* Instance of your custom APNs/local notification manager */  
private var pushManager: AppleNotificationManager!

Enregistrement:

func application(application: UIApplication, didRegisterUserNotificationSettings notificationSettings: UIUserNotificationSettings) {
    // Called to tell the delegate the types of notifications that can be used to get the user’s attention
    pushManager.didRegisterSettings(notificationSettings)
}

func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
    // Tells the delegate that the app successfully registered with Apple Push Notification service (APNs)
    pushManager.didRegisterDeviceToken(deviceToken)
}

func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) {
    // Sent to the delegate when Apple Push Notification service cannot successfully complete the registration process.
    pushManager.didFailToRegisterDeviceToken(error)
}

Traitement des notifications à distance:

func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
    // Remote notification arrived, there is data to be fetched
    // Handling it
    pushManager.handleNotification(userInfo,
                                   background: application.applicationState == .Background
    )
}

Gestion des notifications locales:

func application(application: UIApplication, didReceiveLocalNotification notification: UILocalNotification) {
    pushManager.handleLocalNotification(notification, background: false)
}

Action de manipulation (obsolète):

func application(application: UIApplication, handleActionWithIdentifier identifier: String?, forRemoteNotification userInfo: [NSObject : AnyObject],
                     completionHandler: () -> Void) {
    pushManager.handleInteractiveRemoteNotification(userInfo, actionIdentifier: identifier, completion: completionHandler)
}


Modified text is an extract of the original Stack Overflow Documentation
Sous licence CC BY-SA 3.0
Non affilié à Stack Overflow