El framework de iOS de mPaaS se deriva del framework de desarrollo del cliente Alipay. De acuerdo con el concepto de diseño de Framework, mPaaS iOS aísla la lógica de negocio en varios módulos relativamente independientes y busca lograr una alta cohesión y un bajo acoplamiento entre ellos.
El framework de iOS de mPaaS asume directamente el ciclo de vida de la aplicación. Se encarga del inicio del host, gestiona el ciclo de vida de la aplicación, procesa y distribuye los eventos delegate de UIApplication, y administra de forma unificada cada módulo de negocio (MicroApplication y Services), entre otras funciones.
Este tema presenta una introducción detallada al framework de iOS de mPaaS.
Inicio del host
Al reemplazar la función main del programa, se asume directamente el control del ciclo de vida de la aplicación. El proceso completo de inicio es a continuación:
main -> DFClientDelegate -> Open Launcher application
Gestión del ciclo de vida de la aplicación
Tras integrar el framework de mPaaS, este reemplaza por completo a AppDelegate. El framework gestiona todo el ciclo de vida de la aplicación, pero usted aún puede implementar los métodos delegate en las distintas etapas de dicho ciclo. El framework proporciona acceso a todos los métodos delegate disponibles en UIApplicationDelegate; solo necesita sobrescribir el método correspondiente en la Category.
Los métodos del ciclo de vida se declaran de la siguiente manera (consulte el archivo DTFrameworkInterface.h para obtener más información):
/**
* The framework needs to implement certain initialization logic in didFinishLaunching, but this method will be called before execution.
*/
- (void)application:(UIApplication *)application beforeDidFinishLaunchingWithOptions:(NSDictionary *)launchOptions;
/**
* The framework calls back this method, making the accessed application taking over its own didFinishLaunching logic.
* When DTFrameworkCallbackResultReturnYES or DTFrameworkCallbackResultReturnNO is returned, they are directly returned to the system, without executing the subsequent logic.
* This method is called back before starting BootLoader, application can make the framework exit in advance by returning DTFrameworkCallbackResultReturnYES or DTFrameworkCallbackResultReturnNO, without running the default BootLoader.
* Use the default implementation in the framework, override is normally not required.
*
* @return : To continue run the framework, or return YES/NO to the system.
*/
- (DTFrameworkCallbackResult)application:(UIApplication *)application handleDidFinishLaunchingWithOptions:(NSDictionary *)launchOptions;
/**
* The framework needs to implement certain initialization logic in didFinishLaunching, but this method will be called after all the logics are done.
*/
- (void)application:(UIApplication *)application afterDidFinishLaunchingWithOptions:(NSDictionary *)launchOptions;
/**
* The framework calls back this method in advance, allowing the accessed application to process the notification message in advance.
* When DTFrameworkCallbackResultContinue is returned, the framework broadcasts the message to global listeners through UIApplicationDidReceiveRemoteNotification, and calls completionHandler(UIBackgroundFetchResultNoData).
* When DTFrameworkCallbackResultReturn is returned, it means the accessed application has completely processed the message, and the framework stops executing the subsequent logic.
*/
- (DTFrameworkCallbackResult)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult result))completionHandler;
/**
* The framework calls back this method in advance, allowing the accessed application to process the notification message in advance.
* When DTFrameworkCallbackResultContinue is returned, the framework broadcasts the message to global listeners through UIApplicationDidReceiveLocalNotification.
* When DTFrameworkCallbackResultReturn is returned, it means the accessed application has completely processed the message, and the framework stops executing the subsequent logic.
*/
- (DTFrameworkCallbackResult)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification;
/**
* The framework calls back this method in advance, allowing the accessed application to process the notification message in advance.
* When DTFrameworkCallbackResultContinue is returned, the framework broadcasts the message to global listeners through UIApplicationDidReceiveLocalNotification, and calls completionHandler().
* When DTFrameworkCallbackResultReturn is returned, it means the accessed application has completely processed the message, and the framework stops executing the subsequent logic.
*/
- (DTFrameworkCallbackResult)application:(UIApplication *)application handleActionWithIdentifier:(NSString *)identifier forLocalNotification:(UILocalNotification *)notification completionHandler:(void (^)())completionHandler;
/**
* The framework calls back this method in advance, allowing the accessed application to get deviceToken.
* When DTFrameworkCallbackResultContinue is returned, the framework broadcasts the message to global listeners through UIApplicationDidRegisterForRemoteNotifications.
* When DTFrameworkCallbackResultReturn is returned, it means the accessed application has completely processed, and the framework stops executing the subsequent logic.
*/
- (DTFrameworkCallbackResult)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken;
/**
* The framework calls back this method in advance when it fails to obtain deviceToken.
* When DTFrameworkCallbackResultContinue is returned, the framework continues to execute, no other logic currently.
* When DTFrameworkCallbackResultReturn is returned, the framework stops executing the subsequent logic, no other logic currently.
*/
- (DTFrameworkCallbackResult)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error;
/**
* The framework notifies sharing component (if there is, and shouldAutoactivateShareKit returns YES) in advance, if the sharing component cannot process it, this method is called back to allow the accessed application to process openURL.
* When DTFrameworkCallbackResultReturnYES or DTFrameworkCallbackResultReturnNO is returned, the framework directly returns to the system, without executing the subsequent logic.
* When DTFrameworkCallbackResultContinue is returned, the framework continues to process the URL, and distribute it to SchemeHandler and other classes for further processing.
*
* Comparing with the system method, this method has an additional newURL parameter, allowing the application to return a different URL after processing. If the function returns DTFrameworkCallbackResultContinue and assign value to newURL, the framework will use the new URL for subsequent processing.
*/
- (DTFrameworkCallbackResult)application:(UIApplication *)application openURL:(NSURL *)url newURL:(NSURL **)newURL sourceApplication:(NSString *)sourceApplication annotation:(id)annotation;
/**
* The framework calls back this method in advance.
* When DTFrameworkCallbackResultContinue is returned, the framework continues to execute, no other logic currently.
* When DTFrameworkCallbackResultReturn is returned, the framework stops executing the subsequent logic, no other logic currently.
*/
- (DTFrameworkCallbackResult)applicationWillResignActive:(UIApplication *)application;
/**
* The framework calls back this method in advance.
* When DTFrameworkCallbackResultContinue is returned, the framework continues to execute, no other logic currently.
* When DTFrameworkCallbackResultReturn is returned, the framework stops executing the subsequent logic, no other logic currently.
*/
- (DTFrameworkCallbackResult)applicationDidEnterBackground:(UIApplication *)application;
/**
* The framework calls back this method in advance.
* When DTFrameworkCallbackResultContinue is returned, the framework continues to execute, no other logic currently.
* When DTFrameworkCallbackResultReturn is returned, the framework stops executing the subsequent logic, no other logic currently.
*/
- (DTFrameworkCallbackResult)applicationWillEnterForeground:(UIApplication *)application;
/**
* The framework calls back this method in advance.
* When DTFrameworkCallbackResultContinue is returned, the framework continues to execute and give event to sharing component (if there is, and shouldAutoactivateShareKit returns YES). If the entire application is not loaded, BootLoader is called.
* When DTFrameworkCallbackResultReturn is returned, the framework stops executing the subsequent logic, no other logic currently.
*/
- (DTFrameworkCallbackResult)applicationDidBecomeActive:(UIApplication *)application;
/**
* The framework calls back this method in advance.
* When DTFrameworkCallbackResultContinue is returned, the framework continues to execute, no other logic currently.
* When DTFrameworkCallbackResultReturn is returned, the framework stops executing the subsequent logic, no other logic currently.
*/
- (DTFrameworkCallbackResult)applicationWillTerminate:(UIApplication *)application;
/**
* The framework calls back this method in advance.
* When DTFrameworkCallbackResultContinue is returned, the framework continues to execute, no other logic currently.
* When DTFrameworkCallbackResultReturn is returned, the framework stops executing the subsequent logic, no other logic currently.
*/
- (DTFrameworkCallbackResult)applicationDidReceiveMemoryWarning:(UIApplication *)application;
/**
* The framework calls back this method in advance, allowing the accessed application to process the Watch message in advance.
* When DTFrameworkCallbackResultContinue is returned, the framework broadcasts the Watch message to global listeners through UIApplicationWatchKitExtensionRequestNotifications.
* When DTFrameworkCallbackResultReturn is returned, it means the accessed application has completely processed the message, and the framework stops executing the subsequent logic.
*/
- (DTFrameworkCallbackResult)application:(UIApplication *)application handleWatchKitExtensionRequest:(NSDictionary *)userInfo reply:(void(^)(NSDictionary *replyInfo))reply;
/**
* The framework calls back this method in advance, allowing the accessed application to process the message in advance.
* When DTFrameworkCallbackResultContinue is returned, the framework broadcasts the message to global listeners through UIApplicationUserActivityNotifications, and returns NO to the system in the end.
* When DTFrameworkCallbackResultReturnYES or DTFrameworkCallbackResultReturnNO is returned, the framework directly returns to the system, without executing the subsequent logic.
*/
- (DTFrameworkCallbackResult)application:(UIApplication *)application continueUserActivity:(NSUserActivity *)userActivity restorationHandler:(void(^)(NSArray *restorableObjects))restorationHandler;
/**
* The framework calls back this method in advance, allowing the accessed application to process the message of 3D Touch quick entry in advance.
* When DTFrameworkCallbackResultContinue is returned, the framework processes the URL brought by shortcutItem, and calls completionHandler() to return whether it has been processed.
* When DTFrameworkCallbackResultReturn is returned, the framework directly returns to the system, without executing the subsequent logic.
*/
- (DTFrameworkCallbackResult)application:(UIApplication *)application performActionForShortcutItem:(UIApplicationShortcutItem *)shortcutItem completionHandler:(void (^)(BOOL))completionHandler;
/**
* Background Fetch mechanism callback
* completionHandler must be called back in 30 seconds, otherwise the process will be terminated.
* To enable this mechanism, you need to configure the fetch option of Background Modes, and then call the following method in didFinishLaunching. See documentation for more information.
* [application setMinimumBackgroundFetchInterval:UIApplicationBackgroundFetchIntervalMinimum];
* The default implementation is null, you need to process it in your own way.
*/
- (void)application:(UIApplication *)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler;
División de módulos de la aplicación
El framework de mPaaS define MicroApplication y Service para separar los distintos módulos. Con base en el criterio de "si cuenta o no con una interfaz de usuario", el framework clasifica los diferentes módulos en MicroApplication y Service, e implementa la gestión de su ciclo de vida mediante Context.
|
Término |
Definición |
|
MicroApplication |
Microaplicación con interfaz de usuario que se ejecuta en el cliente durante el tiempo de ejecución |
|
Service |
Servicio ligero y abstracto proporcionado por el cliente durante el tiempo de ejecución |
|
Context |
Contexto del microcomponente del cliente durante el tiempo de ejecución |
Esta sección presenta los conceptos de microaplicación, servicio y contexto. Consulte Create a micro application para obtener más información.
MicroApplication
Durante el desarrollo de aplicaciones basadas en el framework de iOS de mPaaS, generalmente se configura como microaplicación cualquier servicio independiente que cuente con interfaz de usuario (por ejemplo: transferencias, recargas celulares y otros servicios en Alipay). Esto permite aislarlo de otros servicios para lograr una alta independencia y nula interdependencia entre las microaplicaciones.
Cada microaplicación tiene su propio ciclo de vida. El proceso general es a continuación:

Los métodos de callback de la microaplicación a lo largo de todo su ciclo de vida son a continuación (consulte el archivo DTMicroApplicationDelegate.h para obtener más información):
@required
/**
* Request the delegate of application object to return root view controller.
*
* @param application: Application object.
*
* @return: The root view controller of application.
*/
- (UIViewController *)rootControllerInApplication:(DTMicroApplication *)application;
@optional
/**
* Notify the application delegate that the application object has been instantiated.
*
* @param application: Application object.
*/
- (void)applicationDidCreate:(DTMicroApplication *)application;
/**
* Notify the application delegate that the application will be launched.
*
* @param application: Launched application object.
* @param options: Running parameters of the application.
*/
- (void)application:(DTMicroApplication *)application willStartLaunchingWithOptions:(NSDictionary *)options;
/**
* Notify the application delegate that the application is launched already.
*
* @param application: Launched application object.
*/
- (void)applicationDidFinishLaunching:(DTMicroApplication *)application;
/**
* Notify the application delegate that the application will be paused and put into background.
*
* @param application: Launched application object.
*/
- (void)applicationWillPause:(DTMicroApplication *)application;
/**
* Notify the application delegate that the application will be reactivated.
*
* @param application: The application object to be activated.
*/
- (void)application:(DTMicroApplication *)application willResumeWithOptions:(NSDictionary *)options;
/**
* Notify the application delegate that the application has been activated.
*
* @param application: The application object to be activated.
*/
- (void)applicationDidResume:(DTMicroApplication *)application;
/**
* Notify the application delegate that the application has been activated.
*
* @param application: The application object to be activated, together with parameter version.
*/
- (void)application:(DTMicroApplication *)application didResumeWithOptions:(NSDictionary *)options;
/**
* Notify the application delegate that the application will quit.
*
* @param application: Application object.
*/
- (void)applicationWillTerminate:(DTMicroApplication *)application;
/**
* Notify the application delegate that the application will quit.
*
* @param application: Application object.
* @param animated: Whether to quit in animated way.
*/
- (void)applicationWillTerminate:(DTMicroApplication *)application animated:(BOOL)animated;
/**
* Inquire the application delegate whether the application can quit or not.
* Note: The delegate returns **NO** in some special cases. If it defaults to **Yes**, the application can quit.
*
* @param application: Application object.
*
* @return: Whether the application can quit or not.
*/
- (BOOL)applicationShouldTerminate:(DTMicroApplication *)application;
Service
El framework de iOS de mPaaS considera como servicio a cualquier componente del framework que carezca de interfaz de usuario. Las diferencias entre una microaplicación y un servicio son a continuación:
La microaplicación funciona como un proceso de negocio independiente, mientras que el servicio se utiliza para proporcionar funcionalidades generales.
El servicio mantiene estado. Una vez iniciado, existe durante todo el ciclo de vida del cliente y se puede obtener en cualquier momento; la microaplicación se destruye al salir.
Las interfaces relevantes para la gestión de servicios son a continuación (consulte el archivo DTService.h para obtener más información):
@required
/**
* Start a service.
* Note:
* The framework will call the method after initialization.
* The service can start an application only when the method is called.
*/
- (void)start;
@optional
/**
* A service is created.
*/
- (void)didCreate;
/**
* The service will be destroyed.
*/
- (void)willDestroy;
Context
Context es el centro de control de todo el framework del cliente. Gestiona de forma unificada la interacción y la navegación entre microaplicaciones y servicios, con las siguientes responsabilidades:
Proporcionar una interfaz para iniciar la microaplicación. Los usuarios pueden buscar, cerrar y gestionar la navegación de la microaplicación de forma rápida mediante su nombre.
Proporcionar una interfaz para iniciar servicios, así como gestionar su registro, descubrimiento y cancelación de registro.
Gestión de microaplicaciones
Interfaces relevantes para la gestión de microaplicaciones (consulte el archivo
DTContext.hpara obtener más información):
/**
* Start an application as per the given name.
*
* @param name: Name of the application to be started.
* @param params: The parameters need to be forwarded to another application when an application is started.
* @param animated: Specify whether to display animation when starting an application.
*
* @return: Return YES if the application is successfully started, otherwise NO.
*/
- (BOOL)startApplication:(NSString *)name params:(NSDictionary *)params animated:(BOOL)animated;
/**
* Start an application as per the given name.
*
* @param name: Name of the application to be started.
* @param params: The parameters need to be forwarded to another application when an application is started.
* @param launchMode: Specify the method of starting application.
*
* @return: Return YES if the application is successfully started, otherwise NO.
*/
- (BOOL)startApplication:(NSString *)name params:(NSDictionary *)params launchMode:(DTMicroApplicationLaunchMode)launchMode;
/**
* Find the specified application.
*
* @param name: Name of the application to find.
*
* @return: Return corresponding application object if the specified application is in the application stack, otherwise nil.
*/
- (DTMicroApplication *)findApplicationByName:(NSString *)name;
/**
* Return the application which is on the top of the stack currently, namely the application visible to users.
*
* @return: Current visible applications.
*/
- (DTMicroApplication *)currentApplication;
-
Proceso de inicio de la microaplicación:

Gestión de servicios
Interfaces relevantes para la gestión de servicios (consulte el archivo
DTContext.hpara obtener más información):
/**
* Find a service as per the given name.
*
* @param name: Service name
*
* @return: Return a service object if the service with given name is found, otherwise null.
*/
- (id)findServiceByName:(NSString *)name;
/**
* Register a service.
*
* @param name: Service name
*/
- (BOOL)registerService:(id)service forName:(NSString *)name;
/**
* Deregister an existing service.
*
* @param name: Service name
*/
- (void)unregisterServiceForName:(NSString *)name;
-
Proceso de inicio del servicio:

El siguiente diagrama de clases UML ilustra cómo Context gestiona las microaplicaciones y los servicios:
