DEV Community

Alex Spinov
Alex Spinov

Posted on

Capacitor Has a Free API — Here's How to Build Native Mobile Apps with Web Tech

Capacitor by Ionic lets you build native iOS and Android apps using web technologies. It provides a bridge between your web app and native device APIs — camera, geolocation, filesystem, and more.

Getting Started

npm install @capacitor/core @capacitor/cli
npx cap init my-app com.example.myapp
npx cap add ios
npx cap add android
Enter fullscreen mode Exit fullscreen mode

Camera Plugin

import { Camera, CameraResultType, CameraSource } from "@capacitor/camera";

const photo = await Camera.getPhoto({
  quality: 90,
  allowEditing: true,
  resultType: CameraResultType.Uri,
  source: CameraSource.Camera
});

console.log(photo.webPath); // Display in <img> tag
Enter fullscreen mode Exit fullscreen mode

Geolocation

import { Geolocation } from "@capacitor/geolocation";

const position = await Geolocation.getCurrentPosition();
console.log(`Lat: ${position.coords.latitude}`);
console.log(`Lng: ${position.coords.longitude}`);

// Watch position changes
const watchId = await Geolocation.watchPosition({}, (position) => {
  console.log(`Moved to: ${position.coords.latitude}, ${position.coords.longitude}`);
});
Enter fullscreen mode Exit fullscreen mode

Local Storage (Preferences)

import { Preferences } from "@capacitor/preferences";

// Store data
await Preferences.set({ key: "user", value: JSON.stringify({ name: "John" }) });

// Read data
const { value } = await Preferences.get({ key: "user" });
const user = JSON.parse(value);

// Remove
await Preferences.remove({ key: "user" });
Enter fullscreen mode Exit fullscreen mode

Push Notifications

import { PushNotifications } from "@capacitor/push-notifications";

await PushNotifications.requestPermissions();
await PushNotifications.register();

PushNotifications.addListener("registration", (token) => {
  console.log(`Push token: ${token.value}`);
});

PushNotifications.addListener("pushNotificationReceived", (notification) => {
  console.log(`Title: ${notification.title}`);
  console.log(`Body: ${notification.body}`);
});
Enter fullscreen mode Exit fullscreen mode

Filesystem

import { Filesystem, Directory } from "@capacitor/filesystem";

// Write file
await Filesystem.writeFile({
  path: "data/config.json",
  data: JSON.stringify({ theme: "dark" }),
  directory: Directory.Documents
});

// Read file
const result = await Filesystem.readFile({
  path: "data/config.json",
  directory: Directory.Documents
});
Enter fullscreen mode Exit fullscreen mode

Build and Deploy

npm run build          # Build web assets
npx cap sync           # Copy to native projects
npx cap open ios       # Open in Xcode
npx cap open android   # Open in Android Studio
Enter fullscreen mode Exit fullscreen mode

Need to extract or automate web content at scale? Check out my web scraping tools on Apify — no coding required. Or email me at spinov001@gmail.com for custom solutions.

Top comments (0)