Capacitor
Capacitor is Ionics native runtime: it wraps your web app in a tiny native shell and exposes hardware features as TypeScript plugins. The official plugin set covers camera, geolocation, filesystem, push, share, and more; community plugins fill the gaps. Each plugin has matching iOS/Android implementations under the hood.
Photo capture, save to filesystem, share the result
EXAMPLE
// npm i @capacitor/camera @capacitor/filesystem @capacitor/share
import { Camera, CameraResultType, CameraSource } from '@capacitor/camera';
import { Filesystem, Directory, Encoding } from '@capacitor/filesystem';
import { Share } from '@capacitor/share';
// 1) Take a photo (uses the native camera on device, file picker on web)
const photo = await Camera.getPhoto({
quality: 80,
resultType: CameraResultType.DataUrl, // 'base64' or 'uri' also work
source: CameraSource.Camera,
saveToGallery: false,
promptLabelHeader: 'Photo for receipt',
});
// 2) Write the photo bytes to app storage
const base64 = photo.dataUrl!.split(',')[1];
const fileName = \`receipt-${Date.now()}.${photo.format}\`;
const saved = await Filesystem.writeFile({
path: fileName,
data: base64,
directory: Directory.Data,
});
// 3) Read it back as text or convert to a Blob for upload
const read = await Filesystem.readFile({
path: fileName,
directory: Directory.Data,
});
// 4) Share the file via the system share sheet
await Share.share({
title: 'Receipt',
text: 'Latest receipt photo',
url: saved.uri, // native file:// URI
dialogTitle: 'Share receipt',
});
// 5) Capability check before calling — useful when targeting web fallback
import { Capacitor } from '@capacitor/core';
if (Capacitor.isPluginAvailable('Camera')) { /* ... */ }
// 6) Permission patterns:
// iOS: add NSCameraUsageDescription, NSPhotoLibraryUsageDescription to Info.plist
// Android: <uses-permission android:name="android.permission.CAMERA"/> in Manifest
// Capacitor will prompt the user the first time you call getPhoto().
Why it matters
Run `npx cap sync` after every plugin install. The command updates the native projects with the new bridging code; skip it and you get \"plugin not implemented on this platform\" at runtime — every Ionic dev has lost an afternoon to that one.
Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.
Example
Example
npm install @capacitor/core @capacitor/cli npx cap init MyApp com.example.myapp npx cap add ios && npx cap add android npx cap syncTry it Yourself »
Exercise
Sync web build into native projects.
npx cap
Four letters.
Discussion
Loading…