O framework iOS do mPaaS origina-se do framework de desenvolvimento do cliente Alipay. Seguindo o conceito de design de Framework, o mPaaS iOS isola as regras de negócio em múltiplos módulos relativamente independentes para alcançar alta coesão e baixo acoplamento entre eles.
O framework iOS do mPaaS assume diretamente o ciclo de vida da aplicação. Ele gerencia a inicialização do Host, o ciclo de vida da aplicação, o processamento e a distribuição dos eventos de delegate da UIApplication, além de gerenciar cada módulo de negócio (MicroApplication e Services) de forma unificada.
Este tópico apresenta uma introdução detalhada ao framework iOS do mPaaS.
Inicialização do Host
A substituição da função main do programa permite assumir diretamente o ciclo de vida da aplicação. O processo completo de inicialização ocorre da seguinte forma:
main -> DFClientDelegate -> Open Launcher application
Gerenciamento do ciclo de vida da aplicação
Após a integração do framework mPaaS, ele substitui completamente a AppDelegate. O framework gerencia todo o ciclo de vida da aplicação, mas você ainda pode implementar os métodos de delegate nas diferentes etapas desse ciclo. Como o framework fornece acesso a todos os métodos de delegate da UIApplicationDelegate, basta sobrescrever o método correspondente na Category.
A declaração do método de ciclo de vida é a seguinte (consulte o arquivo DTFrameworkInterface.h para mais informações):
/**
* 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;
Divisão dos módulos da aplicação
O framework mPaaS define MicroApplication e Service para separar os diferentes módulos. Com base na existência de uma interface de UI, o Framework classifica os módulos em MicroApplication e Service, gerenciando o ciclo de vida desses módulos por meio do Context.
|
Terminologia |
Definição |
|
MicroApplication |
Microaplicação com interface de UI no cliente durante a execução |
|
Service |
Serviço abstrato e leve fornecido pelo cliente durante a execução |
|
Context |
Contexto do microcomponente do cliente durante a execução |
Esta seção apresenta os conceitos de microaplicação, serviço e contexto. Consulte Criar uma microaplicação para obter mais informações.
MicroApplication
No desenvolvimento de aplicações baseadas no framework iOS do mPaaS, serviços independentes com UI são geralmente definidos como microaplicações (por exemplo: transferência, recarga de celular e outros serviços no Alipay). Essa definição permite isolá-los de outros serviços para alcançar alta independência e interdependência zero entre as microaplicações.
Cada microaplicação possui seu próprio ciclo de vida. O fluxo geral é o seguinte:

Os métodos de callback da microaplicação ao longo de todo o ciclo de vida (consulte o arquivo DTMicroApplicationDelegate.h para mais informações):
@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
O framework iOS do mPaaS considera como Service qualquer componente do Framework sem UI. As diferenças entre MicroApplication e Service são:
A MicroApplication atua como um processo de negócio independente, enquanto o Service fornece serviços de uso geral.
O Service mantém estado. Uma vez iniciado, ele persiste durante todo o ciclo de vida do cliente e pode ser acessado a qualquer momento; já a MicroApplication é destruída após a saída.
Interfaces relevantes para gerenciamento de serviços (consulte o arquivo DTService.h para mais informações):
@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
O Context é o centro de controle de todo o framework cliente. Ele gerencia de forma unificada as interações e navegações entre microaplicações e serviços, com as seguintes responsabilidades:
Fornecer uma interface para iniciar a microaplicação. Os usuários podem localizar, fechar e gerenciar rapidamente a navegação da microaplicação utilizando seu nome;
Oferecer uma interface para iniciar serviços, gerenciando o registro, a descoberta e o cancelamento de registro dos serviços.
Gerenciar microaplicações
Interfaces relevantes para o gerenciamento de microaplicações (consulte o arquivo
DTContext.hpara mais informações):
/**
* 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;
-
Processo de inicialização da microaplicação:

Gerenciamento de serviços
Interfaces relevantes para o gerenciamento de serviços (consulte o arquivo
DTContext.hpara mais informações):
/**
* 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;
-
Processo de inicialização do serviço:

O diagrama de classes UML abaixo ilustra como o Context gerencia a microaplicação e o serviço:
