Search⌘ K

Using Capacitor Plugins

Explore how to use Capacitor plugins within Ionic to access native features like the camera. Learn to set up an Ionic project, configure Capacitor, build services for plugins, manage permissions, and run your app on iOS and Android devices.

Now that we are familiar with both the Capacitor CLI and using the Plugin API, let’s build a sample Ionic application that uses the Capacitor Camera Plugin.

Initial steps

Using the CLI, we create the following Ionic project:

ionic start photo-app blank --type=angular 
cd ./photo-app/

Next, we’ll create a custom service that will be used to manage the Capacitor Camera Plugin API methods, which we store in a subdirectory titled services that will be created as part of the CLI command:

ionic g service services/pictures

Initializing Capacitor

Following from this, we’ll initialize Capacitor (using photosApp as the app name and com.masteringIonic.photos as the app ID), add Android/iOS native platforms, and install the PWA Elements package:

npx cap init photosApp com.masteringIonic.photos
ionic build
npx cap add android
sudo gem install cocoapods
npx cap add ios
npm install @ionic/pwa-elements --save

Our initial configuration is now in place, so we can turn our attention towards developing the actual functionality for the application.

Picture this

Let’s start by amending the src/app/services/pictures.service.ts service as follows (amendments highlighted):

TypeScript 3.3.4
/**
* PicturesService
*
* This class uses the Capacitor API to interact with the device camera and
* photolibrary to capture images for rendering to the application
*/
import { Injectable } from '@angular/core';
import { Camera, CameraResultType, CameraSource } from '@capacitor/camera';
import { DomSanitizer } from '@angular/platform-browser';
@Injectable({
providedIn: 'root'
})
export class PicturesService {
/**
* Creates an instance of PicturesService.
*/
constructor(private sanitizer: DomSanitizer) { }
/**
* Uses the Capacitor getPhoto method to capture images using the device camera
*/
public async selectImageWithCamera(): Promise<any> {
const image: any = await Camera.getPhoto({
quality: 100,
allowEditing: true,
resultType: CameraResultType.DataUrl,
source: CameraSource.Camera
});
return this.sanitizer.bypassSecurityTrustResourceUrl(image && (image.dataUrl));
}
/**
* Uses the Capacitor getPhoto method to capture images using the device photolibrary
*/
public async selectPhotoFromLibrary(): Promise<any> {
const image: any = await Camera.getPhoto({
quality: 100,
allowEditing: false,
resultType: CameraResultType.Uri
});
return image.webPath;
}
}

Within our PicturesService class, we import the necessary Capacitor plugin APIs followed by the DomSanitizer class from the Angular platform-browser package. This will be used to sanitize data that we capture through the Camera plugin API.

We then define two methods - selectImageWithCamera on ...