Ontwikkel een Capacitor-plugin voor aangepaste native functionaliteit
description
Met deze prompt kan ik eenvoudig een aangepaste Capacitor-plugin ontwikkelen die specifieke native functies toevoegt die niet standaard beschikbaar zijn. Dit bespaart tijd, voorkomt veelvoorkomende fouten en helpt me mijn app te verrijken met platform-specifieke mogelijkheden, wat lastig is zonder diepgaande native kennis.
prompt
Help me bij het ontwikkelen van een Capacitor-plugin die aangepaste native functionaliteiten toevoegt aan mijn mobiele app. Geef een voorbeeld van de code voor zowel de native k ...
try_prompt
generate_helper
disclaimerOnPageApi
tags
ai_answers
provider: openai
model: gpt-4.1-nano
Natuurlijk! Hier is een basisvoorbeeld van een Capacitor-plugin die een eenvoudige native functionaliteit biedt: het ophalen van de batterijstatus op iOS. Ik zal de code voor zowel de native kant (Swift) als de JavaScript-kant tonen, samen met de stappen voor integratie en gebruik.
---
### Stap 1: Plugin-structuur aanmaken
Gebruik het CLI-commando om een nieuwe plugin te maken:
```bash
npx @capacitor/cli plugin:generate
```
Volg de prompts om de plugin te configureren, bijvoorbeeld `BatteryStatus`.
---
### Stap 2: Native code (iOS) – Swift
**Bestand: `BatteryStatusPlugin.swift`**
```swift
import Capacitor
import UIKit
@objc(BatteryStatusPlugin)
public class BatteryStatusPlugin: CAPPlugin {
@objc func getBatteryLevel(_ call: CAPPluginCall) {
UIDevice.current.isBatteryMonitoringEnabled = true
let level = UIDevice.current.batteryLevel
if level < 0 {
call.reject("Battery level niet beschikbaar")
} else {
call.resolve([
"batteryLevel": level * 100
])
}
}
}
```
**Registratie in `Plugin.swift` (indien nodig):**
```swift
@objc(BatteryStatusPlugin)
public class BatteryStatusPlugin: CAPPlugin {
// code zoals hierboven
}
```
### Stap 3: JavaScript-kant
Maak een TypeScript-bestand, bijvoorbeeld `battery-status.ts`:
```typescript
import { registerPlugin, PluginObject } from '@capacitor/core';
export interface BatteryStatusPlugin {
getBatteryLevel(): Promise<{ batteryLevel: number }>;
}
const BatteryStatus = registerPlugin<BatteryStatusPlugin>('BatteryStatus');
export default BatteryStatus;
```
### Stap 4: Plugin registreren
In je `capacitor.config.ts` of `capacitor.config.json` voeg je de plugin toe, of zorg dat deze correct wordt geïnstalleerd via npm als je deze publiceert.
---
### Stap 5: Gebruik in je app
In je JavaScript/TypeScript code:
```typescript
import BatteryStatus from './path/to/battery-status';
async function checkBattery() {
try {
const result = await BatteryStatus.getBatteryLevel();
console.log(`Batterij niveau: ${result.batteryLevel}%`);
} catch (error) {
console.error('Fout bij ophalen batterijniveau:', error);
}
}
checkBattery();
```
---
### Samenvatting
1. Maak een nieuwe Capacitor-plugin aan.
2. Voeg native code toe voor iOS (Swift) in het correct bestand.
3. Registreer de plugin in JavaScript met `registerPlugin`.
4. Gebruik de plugin in je app door methodes aan te roepen.
Wil je een voorbeeld voor Android of meer geavanceerde functionaliteiten?
provider: deepseek
model: deepseek-chat
Zeker, ik help je met het ontwikkelen van een Capacitor-plugin. Hier is een complete handleiding met voorbeeldcode:
## Stap 1: Plugin-structuur aanmaken
```bash
npm init @capacitor/plugin custom-plugin
cd custom-plugin
```
## Stap 2: Native iOS Implementatie
**ios/Plugin/CustomPlugin.swift**
```swift
import Capacitor
@objc(CustomPlugin)
public class CustomPlugin: CAPPlugin {
@objc func echo(_ call: CAPPluginCall) {
let value = call.getString("value") ?? ""
call.resolve(["value": value])
}
@objc func getDeviceInfo(_ call: CAPPluginCall) {
let device = UIDevice.current
let result = [
"name": device.name,
"model": device.model,
"systemVersion": device.systemVersion,
"identifierForVendor": device.identifierForVendor?.uuidString ?? ""
]
call.resolve(result)
}
@objc func showNativeAlert(_ call: CAPPluginCall) {
let title = call.getString("title") ?? "Alert"
let message = call.getString("message") ?? ""
DispatchQueue.main.async {
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default))
self.bridge?.viewController?.present(alert, animated: true)
}
call.resolve()
}
}
```
## Stap 3: JavaScript/Typescript Implementatie
**src/web.ts**
```typescript
import { WebPlugin } from '@capacitor/core';
import type { CustomPluginPlugin, DeviceInfo } from './definitions';
export class CustomPluginWeb extends WebPlugin implements CustomPluginPlugin {
async echo(options: { value: string }): Promise<{ value: string }> {
console.log('ECHO', options);
return options;
}
async getDeviceInfo(): Promise<DeviceInfo> {
throw new Error('Method not implemented on web.');
}
async showNativeAlert(options: { title: string; message: string }): Promise<void> {
window.alert(`${options.title}: ${options.message}`);
}
}
```
**src/definitions.ts**
```typescript
export interface CustomPluginPlugin {
echo(options: { value: string }): Promise<{ value: string }>;
getDeviceInfo(): Promise<DeviceInfo>;
showNativeAlert(options: { title: string; message: string }): Promise<void>;
}
export interface DeviceInfo {
name: string;
model: string;
systemVersion: string;
identifierForVendor: string;
}
```
## Stap 4: Main Plugin File
**src/index.ts**
```typescript
import { registerPlugin } from '@capacitor/core';
import type { CustomPluginPlugin } from './definitions';
const CustomPlugin = registerPlugin<CustomPluginPlugin>('CustomPlugin', {
web: () => import('./web').then(m => new m.CustomPluginWeb()),
});
export * from './definitions';
export { CustomPlugin };
```
## Stap 5: Plugin registreren in je app
**In je Capacitor project:**
```bash
npm install ./path/to/custom-plugin
```
**Voeg toe aan android/settings.gradle:**
```gradle
include ':custom-plugin'
project(':custom-plugin').projectDir = new File('../node_modules/custom-plugin/android')
```
**Voeg toe aan android/app/build.gradle:**
```gradle
dependencies {
implementation project(':custom-plugin')
}
```
## Stap 6: Plugin gebruiken in je app
**In je Vue/React/Angular component:**
```typescript
import { CustomPlugin } from 'custom-plugin';
// Voorbeeld gebruik
const useCustomPlugin = () => {
const showAlert = async () => {
try {
await CustomPlugin.showNativeAlert({
title: 'Hallo!',
message: 'Dit is een native alert!'
});
} catch (error) {
console.error('Error showing alert:', error);
}
};
const getDeviceInfo = async () => {
try {
const info = await CustomPlugin.getDeviceInfo();
console.log('Device info:', info);
return info;
} catch (error) {
console.error('Error getting device info:', error);
}
};
return { showAlert, getDeviceInfo };
};
```
## Stap 7: Sync en build
```bash
npx cap sync ios
npx cap sync android
```
## Belangrijke bestanden voor configuratie:
**package.json** (van de plugin):
```json
{
"name": "custom-plugin",
"version": "1.0.0",
"description": "Mijn custom Capacitor plugin",
"main": "dist/plugin.js",
"types": "dist/index.d.ts",
"capacitor": {
"ios": {
"src": "ios"
},
"android": {
"src": "android"
}
}
}
```
**ios/Plugin/CustomPlugin.m** (Objective-C bridge):
```objective-c
#import <Capacitor/Capacitor.h>
CAP_PLUGIN(CustomPlugin, "CustomPlugin",
CAP_PLUGIN_METHOD(echo, CAPPluginReturnPromise);
CAP_PLUGIN_METHOD(getDeviceInfo, CAPPluginReturnPromise);
CAP_PLUGIN_METHOD(showNativeAlert, CAPPluginReturnPromise);
)
```
Dit geeft je een solide basis voor je custom plugin. Vergeet niet om de plugin te testen op zowel iOS als Android, en voeg eventuele Android-specifieke implementaties toe in de android map.