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):
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 ...