大部分的业务逻辑web端都是可以实现的,但是有些必须要用原生才能实现,我这里遇到的问题是集成第三方sdk时,由于第三方平台只提供Android和iOS版本的sdk,所以没有办法在web端集成给多端使用,故此研究了下如何集成到本地也就是原生环境中,在web端调用,步骤如下:
一、添加ios本地代码
1.创建工程 ionic start call-native tabs
2.执行 npm install @capacitor/ios 和 npx cap add ios 、npx cap open ios
3.xcode中创建swift文件名为MyViewController,添加代码
import UIKit
import Capacitor
class MyViewController: CAPBridgeViewController {
public func showYYMainView() {
DispatchQueue.main.async {
self.present(MapViewController(), animated: true) {
print("present success")
}
}
}
}
4.创建MapViewController
5.创建swift文件名称为EchoPlugin并添加代码
import Foundation
import UIKit
import Capacitor
@objc(EchoPlugin)
public class EchoPlugin: CAPPlugin {
@objc func echo(_ call : CAPPluginCall) {
let value = call.getString("value") ?? ""
var myDelegate: AppDelegate
var myVC: MyViewController
myDelegate = UIApplication.shared.delegate as! AppDelegate
myVC = myDelegate.window?.rootViewController as! MyViewController
myVC.showYYMainView()
call.resolve(["value": value])
}
}
6.创建.m文件名称同为EchoPlugin,如果提示“Would you like to configure an Objective-C bridging header?”点击create bridging header创建桥接文件,添加代码
#import <Capacitor/Capacitor.h>
CAP_PLUGIN(EchoPlugin, "Echo",
CAP_PLUGIN_METHOD(echo, CAPPluginReturnPromise);
)
7.vsCode中tab1页面中添加按钮
<ion-button (click)="shoMapViewController()">加载mapViewController</ion-button>
8.tab1.page.ts中添加逻辑代码
import { registerPlugin } from '@capacitor/core';
export interface EchoPlugin {
echo(options: { value: string }): Promise<{ value: string }>;
}
const echo = registerPlugin<EchoPlugin>('Echo');
shoMapViewController() {
this.fetchPlugin();
}
fetchPlugin = async () => {
const { value } = await echo.echo({ value: 'Hello World!' });
};
9.在xcode中运行可看到如下页面,点击按钮可加载map页面,点击dismiss可收回
二、添加Android原生代码
1.执行命令 npm install @capacitor/android、npx cap add android、npx cap open android
2.在Android studio中创建EchoPlugin.java文件,添加如下代码
@CapacitorPlugin(name = "Echo")
public class EchoPlugin extends Plugin {
@PluginMethod()
public void echo(PluginCall call) {
String value = call.getString("value");
JSObject ret = new JSObject();
ret.put("value", value);
Log.e("+++-------:", ret.toString());
Intent intent = new Intent(getContext(), TracingActivity.class);
startActivityForResult(call, intent, "activityResult");
call.resolve(ret);
}
}
3.创建TracingActivity
4.Main Activity中注册
registerPlugin(EchoPlugin.class);
5.运行后如下图,点击首页按钮,web端调用Android 方法并切换页面也正常运行
以上就是在web端通过插件的方式调用ios和Android原生代码并显示页面的逻辑
源码链接如下:
ioniccapacitor调用原生本地代码切换页面-HTML5文档类资源-CSDN下载