API/personalização de componentes
1. Registro APIs personalizadas
Se o applet precisar chamar alguns recursos fornecidos pelo aplicativo host, e o Applet SDK do Phizdclip não será fotografado ou o Cannit será implementado, você poderá registrar uma API personalizada para fazer com que o applet ligue para a API registrada no aplicativo.
O registro de uma API personalizado é dividido em dois Sarnarios:
- Uma API personalizada registrada para uso por applets nativos.
- Uma API personalizada registrada para uso por H5 carregado pelo componente WebView no applet.
1.1 Registre a API assíncrona de applet
Registrando funções para uma API CONSHENCNONOUS
/**
Register Extension Api
@param extApiName Extended api name
@param handler Callback
@return Return registration results
*/
- (BOOL)registerExtensionApi:(NSString *)extApiName handler:(void (^)(FATAppletInfo *appletInfo, id param, FATExtensionApiCallback callback))handler;Para exmple, eu registro um costume PhizClipLogin Aqui para que ele possa ser usado diretamente no applet.
Primeiro, após a integração do SDK no aplicativo, registre o aplicativo personalizado:
[[FATClient sharedClient] registerExtensionApi:@ "PhizClipLogin" handler:^(FATAppletInfo *appletInfo, id param, FATExtensionApiCallback callback) {
// xxxx
callback(FATExtensionCodeSuccess, nil);
}];Então, crie o PhizClipConf.js Arquivo no diretório raiz do applet, com a configuração de amostra a seguir:
module.exports = {
extApi: [
{
//General Interaction API
name: 'PhizClipLogin', //Extended api name The api must be implemented on the Native side
sync: false, //Whether it is synchronous api
params: {
//Extend the parameter format of the api to list only the required properties
url: ''
}
}
]
}NOTA: EXTAPI é uma matriz, para que você possa registrar várias APIs personalizadas.
Para obter informações de configuração de API mais personalizadas, consulte pz.loadExtApi
Por fim, ligue para a API personalizada no applet, código de exemplo:
pz.PhizClipLogin({
url: 'https://www.baidu.com',
success: function(res) {
console.log('Call customEvent success')
console.log(res)
},
fail: function(res) {
console.log('Call customEvent fail')
console.log(res)
}
})1.2 Registre -se para a API de sincronização de applet
Desde 2.36.1, o phizclip applet sdk também suporta registrar APIs síncronas personalizadas.
A função para registrar APIs síncronas personalizadas são:
/**
Register for the Synchronization Extension Api
@param syncExtApiName Extended api name
@param handler Call
@return Return registration results
*/
- (BOOL)registerSyncExtensionApi:(NSString *)syncExtApiName handler:(NSDictionary *(^)(FATAppletInfo *appletInfo, id param))handler;Para o Exmple, registro uma API de applet sincronizada aqui: 1).
1). Após a inicialização do SDK, registre e implemente a API de sincronização.
[[FATClient sharedClient] registerSyncExtensionApi:@ "PhizClipTestSync" handler:^NSDictionary *(FATAppletInfo *appletInfo, id param) {
NSLog(@ "%p, param:%@" , __func__, param);
NSDictionary *resultDict = @{
@ "content" :@ "This is what the sync api returns" ,
@ "title" :@ "This is the title returned by the sync api"
};
return resultDict;
}];2). Crie PhizClipConf.js Arquivo no diretório raiz do applet e adicione a API de sincronização
module.exports = {
extApi: [
{
//General Interaction API
name: 'PhizClipLogin', //Extended api name The api must be implemented on the Native side
sync: false, //Whether it is synchronous api
params: {
//Extend the parameter format of the api to list only the required properties
url: ''
}
},
{
name: 'PhizClipTestSync',
sync: true, // Whether it is synchronous api
params: {
name: '',
title: ''
}
}
]
}3). Ligue para o applet
const res = pz.PhizClipTestSync({ name: 'Zhang San', title: 'PhizClip' })
console.log(res.title)Observe que. A entrada para a API de sincronização personalizada é um dicionário, o valor de retorno também deve ser um tipo de dicionário, e o interior não contém que não pode ser json ized (por exemplo, visualização, modelo personalizado). Os parâmetros delarados nos parâmetros de> phizclipconf.js devem ser passados na chamada. Para exmple, em amostra acima, declarei dois parâmetros, nome e título, se eu usei
const res = pz.PhizClipTestSync({'name':'Zhang San'}),,const res = pz.PhizClipTestSync({}),,const res = pz. PhizClipTestSync()Todos resultarão em um erro relatado e o evento não poderá ser enviado ao nativo. Portanto, os parâmetros em phizdclipconf.js são melhor deixados de fora ou declarados como {}.
1.3 Registre a API JS
A teia-O componente de visualização pode ser usado no applet para carregar o H5 e, se o H5 também parecer uma capacidade da API do host, você poderá usar esse método para registrar um APPI.
/// apiRegister the native api to be called for HTML
/// @param webApiName Native api names
/// @param handler Callback
- (BOOL)fat_registerWebApi:(NSString *)webApiName handler:(void (^)(FATAppletInfo *appletInfo, id param, FATExtensionApiCallback callback))handler;Eu registrei um Medhod Calld js2AppFunction para o H5 no applet aqui.
[[FATClient sharedClient] fat_registerWebApi:@ "js2AppFunction" handler:^(FATAppletInfo *appletInfo, id param, FATExtensionApiCallback callback) {
NSString *name = param[@ "name" ];
// id params = param[@ "data" ];
if ([name isEqualToString:@ "getLocation" ]) {
// Execute positioning logic
// Return results to HTML
NSDictionary *dict = @{@ "errno" :@ "403" , @ "errmsg" :@ "No permission" , @ "result" : @{@ "address" :@ "Aerospace Technology Plaza, Nanshan District, Shenzhen, Guangdong Province" }};
callback(FATExtensionCodeSuccess, dict);
} else if ([name isEqualToString:@ "getColor" ]) {
// Execute other logic
// Return results to HTML
NSDictionary *dict = @{@ "r" :@ "110" ,@ "g" :@ "150" ,@ "b" :@ "150" };
callback(FATExtensionCodeSuccess, dict);
}
}];Faça referência à nossa ponte JSSDK Arquivo no H5, você pode ligar para o método Sobre Registrado.
Exemplo de chamar o método registrado de com o html:
window.pz.miniProgram.callNativeAPI(
'js2AppFunction',
{ name: 'getLocation' },
result => {
console.log(result)
}
)2. chamadas nativas para a API JS
Similaly Se o aplicativo da casa for necessário chamar um método no H5 carregado pelo applet, ele pode usar essa API.
/**
Native calls to JS functions in HTML (applets running in the foreground)
@param eventName Function Name
@param paramString The function's parameter dictionary converted to json
@param pageId webView ID, can not be passed, default call H5 function in the topmost page
@param handler Callback result: error code is FATErrorCodeAppletNotFound, the applet running in the foreground was not found
*/
- (void)fat_callWebApi:(NSString *)eventName paramString:(NSString *)paramString pageId:(NSNumber *)pageId handler:(void (^)(id result, NSError *error))handler;
/**
Native calls to JS functions in HTML (appletId specified by applet)
@param eventName Function Name
@param appletId Small program publishing process
@param paramString The function's parameter dictionary converted to json
@param pageId webView ID, can not be passed, default call H5 function in the topmost page
@param handler Callback result: error code is FATErrorCodeAppletNotFound, the applet running in the foreground was not found
*/
- (void)fat_callWebApi:(NSString *)eventName applet:(NSString *)appletId paramString:(NSString *)paramString pageId:(NSNumber *)pageId handler:(void (^)(id result, NSError *error))handler;Primeiro, faça referência a nossa ponte JSSDK arquivo dentro de H5.
Em seguida, registre o método em HTML, por exemplo, o nome do método é app2jsFunction Então então
window.pz.registNativeAPIHandler('app2jsFunction', function(res) {
// app2jsFunction callback
})Finalmente, o lado nativo chama a seguinte API para chamar as funções JS no HTML:
NSString *jsonParams = @ "" ; //Here it should be the json string converted from the parameter dictionary.
NSNumber *pageId = @(1234); //Here is the pageId passed from the HTML
[[FATClient sharedClient] fat_callWebApi:@ "app2jsFunction" paramString:jsonParams pageId:pageId handler:^(id result, NSError *error) {
}];3. Registrando componentes nativos
Devido a recursos limitados, a implementação de componentes nativos, como LivePusher e LivePlayer, pode exigir o uso de terceiro externo-Controles da parte, que podem ser registrados como componentes nativos. Agora apoiamos o registro de três componentes nativos: câmera, LivePlayer e LivePusher.
3.1 Implementando componentes nativos personalizados
Primeiro, crie a visualização do componente e implemente seus métodos de protocolo.
.h
#import <UIKit/UIKit.h>
#import <FinApplet/FATAppletNativeProtocol.h>
NS_ASSUME_NONNULL_BEGIN
@interface FATNativeView : UIView <FATAppletNativeViewProtocol>
@property (nonatomic, strong) NSNumber *nativeViewId;
@property (nonatomic, strong) NSString *type;
@end
@interface FATNativeCameraView : FATNativeView <FATAppletNativeCameraProtocol>
@end
@interface FATNativeLivePlayerView : FATNativeView <FATAppletNativeLivePlayerProtocol>
@end
@interface FATNativeLivePusherView : FATNativeView <FATAppletNativeLivePusherProtocol>
@end
NS_ASSUME_NONNULL_END.m
@implementation FATNativeView
+ (UIView *)onCreateView:(NSDictionary *)param {
return [[self alloc] initWithParam:param];
}
- (instancetype)initWithParam:(NSDictionary *)param {
CGRect frame = CGRectZero;
NSDictionary *style = [param objectForKey:@ "style" ];
if (style) {
CGFloat x = [[style objectForKey:@ "left" ] floatValue];
CGFloat y = [[style objectForKey:@ "top" ] floatValue];
CGFloat height = [[style objectForKey:@ "height" ] floatValue];
CGFloat width = [[style objectForKey:@ "width" ] floatValue];
frame = CGRectMake(x, y, width, height);
}
self = [super initWithFrame:frame];
if (self) {
_type = param[@ "type" ];
_nativeViewId = param[@ "nativeViewId" ];
}
return self;
}
- (void)onUpdateView:(NSDictionary *)param {
NSDictionary *style = [param objectForKey:@ "style" ];
if (style) {
CGRect frame = CGRectZero;
CGFloat x = [[style objectForKey:@ "left" ] floatValue];
CGFloat y = [[style objectForKey:@ "top" ] floatValue];
CGFloat height = [[style objectForKey:@ "height" ] floatValue];
CGFloat width = [[style objectForKey:@ "width" ] floatValue];
frame = CGRectMake(x, y, width, height);
self.frame = frame;
}
}
- (void)onDestroyView:(NSDictionary *)param {
NSLog(@ "Destroyed%@" ,param);
}
@end
@implementation FATNativeCameraView
- (void)setCameraZoom:(NSDictionary *)param success:(FATNativeCallback)callBack {
}
@end
@implementation FATNativeLivePlayerView
@end
@implementation FATNativeLivePusherView
@endEm seguida, defina a classe de visualização do componente
[FATClient sharedClient].nativeViewManager.cameraClass = [FATNativeCameraView class];
[FATClient sharedClient].nativeViewManager.livePlayerClass = [FATNativeLivePlayerView class];
[FATClient sharedClient].nativeViewManager.livePusherClass = [FATNativeLivePusherView class];3.2 Enviando mensagens para componentes nativamente
O aplicativo host envia mensagens para o componente nativo através do NativeViewManager.
/// Send events to nativeView (applets running in the foreground)
/// @param eventName Event Name
/// @param nativeViewId native-view id
/// @param detail Event detail parameters
/// @param completion Completion callback: error code is FATErrorCodeAppletNotFound, the applet running in the foreground was not found
- (void)sendEvent:(NSString *)eventName nativeViewId:(NSNumber *)nativeViewId detail:(NSDictionary *)detail completion:(void (^)(id result, NSError *error))completion;
/// Send event to nativeView (appletId specified by applet)
/// @param eventName Event Name
/// @param appletId AppId of the applet, cannot be empty
/// @param nativeViewId native-view id
/// @param detail Event detail parameters
/// @param completion Completion callback: error code is FATErrorCodeForegroundAppletNotFound, appletId specified applet was not found
- (void)sendEvent:(NSString *)eventName applet:(NSString *)appletId nativeViewId:(NSNumber *)nativeViewId detail:(NSDictionary *)detail completion:(void (^)(id result, NSError *error))completion;Código de amostra
[[FATClient sharedClient].nativeViewManager sendEvent:@ "eventName" nativeViewId:@(1234) detail:@{} completion:^(id result, FATError *error) {
}];3.3 Envie mensagens globais para applets nativamente
/// Send global events (applets running in the foreground)
/// @param detail Event detail parameters
/// @param completion Completion callback: error code is FATErrorCodeAppletNotFound, the applet running in the foreground was not found
- (void)sendCustomEventWithDetail:(NSDictionary *)detail completion:(void (^)(id result, NSError *error))completion;
/// Send global events (applets running in the foreground)
/// @param detail Event detail parameters
/// @param appletId AppId of the applet, cannot be empty
/// @param completion Completion callback: error code is FATErrorCodeForegroundAppletNotFound, appletId specified applet was not found
- (void)sendCustomEventWithDetail:(NSDictionary *)detail applet:(NSString *)appletId completion:(void (^)(id result, NSError *error))completion;Exemplo Código:
[[FATClient sharedClient].nativeViewManager sendCustomEventWithDetail:@{} completion:^(id result, NSError *error) {
}];