Buscar..


Introducción

AppDelegate es un protocolo que define métodos que son llamados por el objeto de UIA singleton UIA en respuesta a eventos importantes en la vida de una aplicación.

Normalmente se utiliza para realizar tareas en el inicio de la aplicación (configuración del entorno de la aplicación, analitycs (ej .: Mixpanel / GoogleAnalytics / Crashlitics), DB stack, etc.) y cierre (ej .: guardar el contexto DB), manejo de solicitudes abiertas de URL y aplicaciones similares Tareas.

Todos los estados de aplicación a través de métodos AppDelegate

Para recibir actualizaciones o para hacer algo antes de que la aplicación se convierta en un usuario, puede utilizar el método que se encuentra debajo.

AppDidFinishLaunching

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

Mientras la aplicación entra en primer plano:

- (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.
}

Al iniciar la aplicación y también al fondo para el método de golpe de primer plano:

- (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.
}

Mientras la aplicación ingrese en segundo plano:

- (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.
}

Mientras que la aplicación renuncia activa

- (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.
}

Mientras que la aplicación termina:

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

Roles de AppDelegate:

  • AppDelegate contiene el startup code su aplicación.
  • Responde a key changes en el state de su aplicación. Específicamente, responde tanto a las interrupciones temporales como a los cambios en el estado de ejecución de la aplicación, como cuando la aplicación pasa del primer plano al fondo.
  • responds to notifications originan desde fuera de la aplicación, como notificaciones remotas (también conocidas como notificaciones push), advertencias de poca memoria, notificaciones de finalización de descargas y más.
  • Se determines si la state preservation y de restoration deben producirse y ayuda en el proceso de conservación y restauración, según sea necesario.
  • responds to events que se dirigen a la aplicación en sí y no son específicos de las vistas o controladores de su aplicación. Puede usarlo para almacenar los objetos de datos centrales de su aplicación o cualquier contenido que no tenga un controlador de vista propietario.

Abrir un recurso especificado por URL

Pide al delegado que abra un recurso especificado por una URL y proporciona un diccionario de opciones de inicio.

Ejemplo de uso:

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

Manejo de notificaciones locales y remotas

Ejemplo de uso:

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

Registro:

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)
}

Manejo remoto de notificaciones:

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
    )
}

Manejo de notificaciones locales:

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

Acción de manejo (en desuso):

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
Licenciado bajo CC BY-SA 3.0
No afiliado a Stack Overflow