iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

Native Plugins

Ionic + Capacitor native plugins: install, sync, call, and the patterns for cross-platform native access.

Ionic — native plugins

EXAMPLE
# ===== Install a plugin =====
npm install @capacitor/camera @capacitor/geolocation @capacitor/preferences
npx cap sync                          # propagate to native projects

# ===== Use in TypeScript =====
import { Camera, CameraResultType, CameraSource } from '@capacitor/camera';

async function takePhoto() {
  const photo = await Camera.getPhoto({
    quality: 90,
    allowEditing: false,
    resultType: CameraResultType.Uri,
    source: CameraSource.Camera,
  });
  return photo.webPath;
}

# ===== Permissions =====
import { Camera } from '@capacitor/camera';
const perms = await Camera.checkPermissions();
if (perms.camera !== 'granted') {
  await Camera.requestPermissions();
}

# ===== Platform detection =====
import { Capacitor } from '@capacitor/core';

if (Capacitor.isNativePlatform()) {
  // iOS or Android
} else {
  // Web
}

if (Capacitor.getPlatform() === 'ios') { /* ... */ }

# ===== Web fallbacks =====
// Many plugins (Camera, Geolocation, Filesystem) ship web implementations.
// Test both contexts; do not assume native-only behaviour.

# ===== Filesystem =====
import { Filesystem, Directory } from '@capacitor/filesystem';

await Filesystem.writeFile({
  path: 'log.txt',
  data: 'hello',
  directory: Directory.Data,
  encoding: 'utf8',
});

const file = await Filesystem.readFile({ path: 'log.txt', directory: Directory.Data, encoding: 'utf8' });

# ===== Preferences (small key-value) =====
import { Preferences } from '@capacitor/preferences';
await Preferences.set({ key: 'theme', value: 'dark' });
const { value } = await Preferences.get({ key: 'theme' });

# ===== Local notifications =====
import { LocalNotifications } from '@capacitor/local-notifications';

await LocalNotifications.requestPermissions();
await LocalNotifications.schedule({
  notifications: [
    { id: 1, title: 'Reminder', body: 'Time to drink water', schedule: { at: new Date(Date.now() + 60 * 1000) } },
  ],
});

# ===== Geolocation =====
import { Geolocation } from '@capacitor/geolocation';

const pos = await Geolocation.getCurrentPosition({ enableHighAccuracy: true });
console.log(pos.coords.latitude, pos.coords.longitude);

# ===== Adding native code (for plugins that need it) =====
# Some plugins require Info.plist (iOS) or AndroidManifest.xml entries.
# Camera example (iOS): add NSCameraUsageDescription string to Info.plist.
# Android: <uses-permission android:name="android.permission.CAMERA" /> in manifest.

# Always: npx cap sync after install + native config edits.

# ===== Building your own plugin =====
npm init @capacitor/plugin@latest

# Generated structure has TS API + iOS Swift + Android Java/Kotlin templates.
# Useful when no community plugin exists.

# ===== Common pitfalls =====
# - Forgetting 'npx cap sync' after install -> JS works, native code missing
# - Missing Info.plist / Manifest entries -> permission requests fail silently
# - Web fallback differs from native (test both!)
# - Plugin version mismatch with @capacitor/core -> runtime errors

# ===== Patterns to internalise =====
# - Always pair install with 'npx cap sync'
# - Check permissions BEFORE calling methods
# - Wrap plugins in service classes (auth, photos, location)
# - Pin plugin + core versions; bump together

# ===== Where to find plugins =====
# - Official: capacitorjs.com/docs/apis
# - Community: github.com/capacitor-community, capawesome.io
# - Awesome list: github.com/riderx/awesome-capacitor

Why it matters

Capacitor plugins bridge native APIs to JS in one package. Install + sync + call. Check permissions, set up Info.plist / Manifest entries, and handle web fallbacks. Wrap in service classes for testability — the same pattern as any other DI in your app.

Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.

Example

Example
// Bridge to native via a Capacitor plugin.
npx @capacitor/cli plugin:generate MyPlugin
// Then implement Java/Kotlin (Android) + Swift (iOS).
Try it Yourself »

Discussion

Loading…