### Install Dependencies and Start Development Server Source: https://github.com/ionic-team/capacitor-docs/blob/main/CONTRIBUTING.md Installs project dependencies and starts the local development server for viewing the Capacitor documentation. Requires recent versions of npm (8+) and Node.js (16+). ```shell npm install npm start ``` -------------------------------- ### Install Xcode Command Line Tools Source: https://github.com/ionic-team/capacitor-docs/blob/main/docs/main/getting-started/environment-setup.md Installs the necessary command-line tools for Xcode, which are required for building and testing iOS applications with Capacitor. ```bash xcode-select --install ``` -------------------------------- ### Install Keyboard Plugin Source: https://github.com/ionic-team/capacitor-docs/blob/main/docs/apis/keyboard.md Install the Keyboard plugin and sync Capacitor. ```bash npm install @capacitor/keyboard npx cap sync ``` -------------------------------- ### Install Capacitor Motion Plugin Source: https://github.com/ionic-team/capacitor-docs/blob/main/docs/apis/motion.md Installs the @capacitor/motion package and synchronizes Capacitor plugins. This is the initial setup step for using the motion API. ```bash npm install @capacitor/motion npx cap sync ``` -------------------------------- ### Install Local LLM Plugin Source: https://github.com/ionic-team/capacitor-docs/blob/main/docs/apis/local-llm.md Install the plugin and sync Capacitor. ```bash npm install @capacitor/local-llm npx cap sync ``` -------------------------------- ### Verify Xcode Command Line Tools Installation Source: https://github.com/ionic-team/capacitor-docs/blob/main/docs/main/getting-started/environment-setup.md Confirms that the Xcode Command Line Tools have been successfully installed by displaying their path. This is crucial for iOS development. ```bash xcode-select -p # /Applications/Xcode.app/Contents/Developer ``` -------------------------------- ### Verify Node.js Installation Source: https://github.com/ionic-team/capacitor-docs/blob/main/docs/main/getting-started/environment-setup.md Checks if Node.js is installed and displays its version. This is a core requirement for Capacitor development. ```bash node --version # v22.21.1 ``` -------------------------------- ### Install and Build Project Source: https://github.com/ionic-team/capacitor-docs/blob/main/README.md Commands to install dependencies, build the project, and serve it in development mode. Assumes Node.js and npm are already installed. ```bash npm install npm run build npm run serve ``` -------------------------------- ### Plugin Load Method (Swift) Source: https://github.com/ionic-team/capacitor-docs/blob/main/docs/plugins/creating-plugins/ios-guide.md Provides an example of implementing the `load()` method in a Capacitor plugin. This method is executed when the plugin is first loaded and can be used for setup tasks. ```swift override public func load() { } ``` -------------------------------- ### Install Browser Plugin Source: https://github.com/ionic-team/capacitor-docs/blob/main/docs/apis/browser.md Commands to install the plugin and sync native projects. ```bash npm install @capacitor/browser npx cap sync ``` -------------------------------- ### Install Action Sheet Plugin Source: https://github.com/ionic-team/capacitor-docs/blob/main/docs/apis/action-sheet.md Install the package and sync the project to apply native changes. ```bash npm install @capacitor/action-sheet npx cap sync ``` -------------------------------- ### Install Haptics Plugin Source: https://github.com/ionic-team/capacitor-docs/blob/main/docs/apis/haptics.md Commands to install the plugin and sync it with the native project. ```bash npm install @capacitor/haptics npx cap sync ``` -------------------------------- ### Install InAppBrowser Plugin Source: https://github.com/ionic-team/capacitor-docs/blob/main/docs/apis/inappbrowser.md Install the InAppBrowser plugin and sync Capacitor. ```bash npm install @capacitor/inappbrowser npx cap sync ``` -------------------------------- ### Install Local Notifications Source: https://github.com/ionic-team/capacitor-docs/blob/main/docs/apis/local-notifications.md Install the Local Notifications plugin and sync Capacitor. ```bash npm install @capacitor/local-notifications npx cap sync ``` -------------------------------- ### Verify CocoaPods Installation Source: https://github.com/ionic-team/capacitor-docs/blob/main/docs/main/getting-started/environment-setup.md Checks if CocoaPods has been installed correctly and displays its version. This is useful for confirming the dependency manager is ready for use. ```bash pod --version # 1.12.1 ``` -------------------------------- ### Install Capacitor App Plugin Source: https://github.com/ionic-team/capacitor-docs/blob/main/docs/apis/app.md Install the plugin package and sync the project with native platforms. ```bash npm install @capacitor/app npx cap sync ``` -------------------------------- ### Install Screen Reader Capacitor Plugin Source: https://github.com/ionic-team/capacitor-docs/blob/main/docs/apis/screen-reader.md Installs the Screen Reader plugin using npm and synchronizes Capacitor plugins. This is the initial setup step for using the screen reader functionality. ```bash npm install @capacitor/screen-reader npx cap sync ``` -------------------------------- ### Install Capacitor Status Bar Plugin Source: https://github.com/ionic-team/capacitor-docs/blob/main/docs/apis/status-bar.md Install the plugin using npm and sync Capacitor. ```bash npm install @capacitor/status-bar npx cap sync ``` -------------------------------- ### Install Push Notifications Plugin Source: https://github.com/ionic-team/capacitor-docs/blob/main/docs/apis/push-notifications.md Install the plugin using npm and sync with native projects. ```bash npm install @capacitor/push-notifications npx cap sync ``` -------------------------------- ### Install Capacitor Geolocation Plugin Source: https://github.com/ionic-team/capacitor-docs/blob/main/docs/apis/geolocation.md Install the plugin using npm and sync Capacitor. ```bash npm install @capacitor/geolocation npx cap sync ``` -------------------------------- ### Install Filesystem Plugin Source: https://github.com/ionic-team/capacitor-docs/blob/main/docs/apis/filesystem.md Installs the Filesystem plugin using npm and synchronizes Capacitor configurations. ```bash npm install @capacitor/filesystem npx cap sync ``` -------------------------------- ### Install Latest Official Plugin Source: https://github.com/ionic-team/capacitor-docs/blob/main/docs/plugins/official.md Installs the most recent version of an official Capacitor plugin. Use this for general installations. ```bash npm install @capacitor/camera@latest ``` -------------------------------- ### List Installed Plugins Source: https://github.com/ionic-team/capacitor-docs/blob/main/docs/cli/commands/ls.md Use this command to see all plugins installed in your Capacitor project. Optionally specify a platform like 'android' or 'ios' to filter results. ```bash npx cap ls [] ``` -------------------------------- ### Install Capacitor Share Plugin Source: https://github.com/ionic-team/capacitor-docs/blob/main/docs/apis/share.md Installs the Capacitor Share plugin and synchronizes native project files. This is a prerequisite for using the Share API. ```bash npm install @capacitor/share npx cap sync ``` -------------------------------- ### Install Capacitor Clipboard Plugin Source: https://github.com/ionic-team/capacitor-docs/blob/main/docs/apis/clipboard.md Commands to install the Capacitor Clipboard plugin and sync native projects. This is a prerequisite for using the plugin's functionality. ```bash npm install @capacitor/clipboard npx cap sync ``` -------------------------------- ### Install Homebrew Package Manager Source: https://github.com/ionic-team/capacitor-docs/blob/main/docs/main/getting-started/environment-setup.md Installs Homebrew, a package manager for macOS, which is a prerequisite for installing CocoaPods and other native iOS packages. ```bash /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)" ``` -------------------------------- ### Install CocoaPods with Homebrew Source: https://github.com/ionic-team/capacitor-docs/blob/main/docs/main/getting-started/environment-setup.md Installs CocoaPods, a dependency manager for native iOS projects, using the Homebrew package manager. This is an optional but common dependency for iOS development. ```bash brew install cocoapods ``` -------------------------------- ### Install Barcode Scanner Plugin Source: https://github.com/ionic-team/capacitor-docs/blob/main/docs/apis/barcode-scanner.md Installs the @capacitor/barcode-scanner package and synchronizes native project files. This is the initial setup step for using the plugin in a Capacitor project. ```bash npm install @capacitor/barcode-scanner npx cap sync ``` -------------------------------- ### Install CocoaPods without Homebrew Source: https://github.com/ionic-team/capacitor-docs/blob/main/docs/main/getting-started/environment-setup.md Installs CocoaPods directly using Ruby Gem, providing an alternative method if Homebrew is not used. This is for users who prefer not to use Homebrew for dependency management. ```bash sudo gem install cocoapods ``` -------------------------------- ### Perform HTTP GET Request with CapacitorHttp Source: https://github.com/ionic-team/capacitor-docs/blob/main/docs/apis/http.md Example of making a GET request using the CapacitorHttp plugin. It demonstrates setting request options like URL, headers, and parameters, and handling the response. ```typescript import { CapacitorHttp } from '@capacitor/core'; // Example of a GET request const doGet = async () => { const options = { url: 'https://example.com/my/api', headers: { 'X-Fake-Header': 'Fake-Value' }, params: { size: 'XL' }, }; const response: HttpResponse = await CapacitorHttp.get(options); // or... // const response = await CapacitorHttp.request({ ...options, method: 'GET' }) }; ``` -------------------------------- ### Build native project with Capacitor CLI Source: https://github.com/ionic-team/capacitor-docs/blob/main/docs/cli/commands/build.md Executes the build process for a specified native platform. ```bash npx cap build [options] ``` -------------------------------- ### Capacitor Cookies API Examples Source: https://github.com/ionic-team/capacitor-docs/blob/main/docs/apis/cookies.md Provides TypeScript examples for interacting with the Capacitor Cookies API. It showcases functions for getting, setting, deleting, clearing cookies at specific URLs, and clearing all cookies. ```typescript import { CapacitorCookies } from '@capacitor/core'; const getCookies = () => { return document.cookie; }; const setCookie = () => { document.cookie = key + '=' + value; }; const setCapacitorCookie = async () => { await CapacitorCookies.setCookie({ url: 'http://example.com', key: 'language', value: 'en', }); }; const deleteCookie = async () => { await CapacitorCookies.deleteCookie({ url: 'https://example.com', key: 'language', }); }; const clearCookiesOnUrl = async () => { await CapacitorCookies.clearCookies({ url: 'https://example.com', }); }; const clearAllCookies = async () => { await CapacitorCookies.clearAllCookies(); }; ``` -------------------------------- ### Choose Media from Gallery Source: https://github.com/ionic-team/capacitor-docs/blob/main/docs/apis/camera.md Allow users to select photos or videos from their device's gallery. This example demonstrates how to configure media type, enable multiple selections, set a limit, and include metadata. It logs details for each selected item. ```typescript import { Camera, MediaTypeSelection } from '@capacitor/camera'; const pickMedia = async () => { try { const { results } = await Camera.chooseFromGallery({ mediaType: MediaTypeSelection.All, // photos, videos, or both allowMultipleSelection: true, limit: 5, includeMetadata: true, }); for (const item of results) { console.log('Type:', item.type); // MediaType.Photo or MediaType.Video console.log('webPath:', item.webPath); console.log('Format:', item.metadata?.format); console.log('Size:', item.metadata?.size); } } catch (e) { const error = e as any; const message = error.code ? `[${error.code}] ${error.message}` : error.message; console.error('chooseFromGallery failed:', message); } }; ``` -------------------------------- ### Mocking Capacitor Storage Get Method in Jest Source: https://github.com/ionic-team/capacitor-docs/blob/main/docs/main/guides/mocking-plugins.md Shows how to mock the `get` method of the Capacitor Storage plugin within a Jest test. This example uses `jest.fn().mockImplementation` to control the return values based on the input key, allowing for specific test scenarios. ```typescript Storage.get = jest.fn().mockImplementation( async (data: { key: string }): Promise<{ value: string }> => { return data.key === "firstName" ? { value: "Jimmy" } : data.key === "lastName" ? { value: "Simms" } : { value: "unknown" }; } ); ``` -------------------------------- ### Update Plugin Documentation (README.md) Source: https://github.com/ionic-team/capacitor-docs/blob/main/docs/plugins/tutorial/packaging.md Installs the plugin and synchronizes it with the Capacitor project. This is a crucial step for ensuring the plugin is correctly integrated into the native projects (iOS and Android). ```bash npm install @capacitor-community/screen-orientation npx cap sync ``` -------------------------------- ### Run Capacitor command Source: https://github.com/ionic-team/capacitor-docs/blob/main/docs/cli/commands/run.md Executes the sync, build, and deployment process for a specified platform. ```bash npx cap run [options] ``` -------------------------------- ### Get Capacitor Configuration in Android Source: https://github.com/ionic-team/capacitor-docs/blob/main/docs/main/reference/core-apis/android.md Shows how to retrieve the configuration object known to the Capacitor runtime on Android. This configuration is essential for understanding the app's setup. ```java public CapConfig getConfig() ``` -------------------------------- ### Register Plugin Methods in Swift Source: https://github.com/ionic-team/capacitor-docs/blob/main/docs/plugins/creating-plugins/ios-guide.md Registers plugin methods with Capacitor, making them available to the web runtime. This example shows how to register an 'echo' method that returns a Promise. ```swift public let pluginMethods: [CAPPluginMethod] = [ CAPPluginMethod(name: "echo", returnType: CAPPluginReturnPromise) ] ``` -------------------------------- ### Open Browser Window Source: https://github.com/ionic-team/capacitor-docs/blob/main/docs/apis/browser.md Example of opening a URL using the Browser plugin. ```typescript import { Browser } from '@capacitor/browser'; const openCapacitorSite = async () => { await Browser.open({ url: 'http://capacitorjs.com/' }); }; ``` -------------------------------- ### CLI Command - cap ls Source: https://github.com/ionic-team/capacitor-docs/blob/main/docs/cli/commands/ls.md Lists all installed Cordova and Capacitor plugins for the project. ```APIDOC ## CLI Command: cap ls ### Description List all installed Cordova and Capacitor plugins. ### Usage ```bash npx cap ls [] ``` ### Parameters #### Path Parameters - **platform** (string) - Optional - The platform to filter by (e.g., 'android', 'ios'). ``` -------------------------------- ### Migrate downloadFile from Filesystem to File Transfer Plugin Source: https://github.com/ionic-team/capacitor-docs/blob/main/docs/apis/filesystem.md Demonstrates migrating file download functionality from the deprecated Filesystem plugin to the new File Transfer plugin, including installation and usage examples for both before and after the migration. ```typescript import { Filesystem, Directory } from '@capacitor/filesystem'; await Filesystem.downloadFile({ url: 'https://example.com/file.pdf', path: 'downloaded-file.pdf', directory: Directory.Documents, progress: true }); // Progress events Filesystem.addListener('progress', (progress) => { console.log(`Downloaded ${progress.bytes} of ${progress.contentLength}`); }); ``` ```typescript import { FileTransfer } from '@capacitor/file-transfer'; import { Filesystem, Directory } from '@capacitor/filesystem'; const fileInfo = await Filesystem.getUri({ directory: Directory.Documents, path: 'downloaded-file.pdf' }); await FileTransfer.downloadFile({ url: 'https://example.com/file.pdf', path: fileInfo.uri, progress: true }); // Progress events FileTransfer.addListener('progress', (progress) => { console.log(`Downloaded ${progress.bytes} of ${progress.contentLength}`); }); ``` -------------------------------- ### Handle Unimplemented Functionality in Capacitor Plugin (TypeScript) Source: https://github.com/ionic-team/capacitor-docs/blob/main/docs/plugins/creating-plugins/web-guide.md Provides an example of throwing an 'unimplemented' error for functionality that is not yet implemented on a specific platform, such as the web. This is useful for stubbing methods or indicating platform limitations. ```typescript async getLocation(): Promise { throw this.unimplemented('Not implemented on web.'); } ``` -------------------------------- ### Example Capacitor Device Plugin Usage Source: https://github.com/ionic-team/capacitor-docs/blob/main/docs/apis/device.md Demonstrates how to import and use the Capacitor Device plugin in TypeScript to retrieve device and battery information. It shows asynchronous calls to get device details and battery status. ```typescript import { Device } from '@capacitor/device'; const logDeviceInfo = async () => { const info = await Device.getInfo(); console.log(info); }; const logBatteryInfo = async () => { const info = await Device.getBatteryInfo(); console.log(info); }; ``` -------------------------------- ### Listen for Plugin Events in TypeScript Source: https://github.com/ionic-team/capacitor-docs/blob/main/docs/plugins/creating-plugins/android-guide.md This TypeScript code snippet shows how to attach an event listener to a Capacitor plugin to receive events emitted from the native side. It demonstrates adding a listener and provides an example of how to remove it later. ```typescript import { MyPlugin } from 'my-plugin'; MyPlugin.addListener('myPluginEvent', (info: any) => { console.log('myPluginEvent was fired'); }); ``` ```typescript import { MyPlugin } from 'my-plugin'; const myPluginEventListener = await MyPlugin.addListener( 'myPluginEvent', (info: any) => { console.log('myPluginEvent was fired'); }, ); myPluginEventListener.remove(); ``` -------------------------------- ### Add FirebaseFirestore Dependency to Capacitor iOS Plugin (.podspec) Source: https://github.com/ionic-team/capacitor-docs/blob/main/docs/plugins/creating-plugins/ios-guide.md This example shows how to add a dependency for `FirebaseFirestore` to a Capacitor iOS plugin using a `.podspec` file. It specifies a version range that includes 11.8.0 or newer, but less than 12.0.0. ```ruby s.dependency 'Capacitor' s.dependency 'FirebaseFirestore', '~> 11.8' ``` -------------------------------- ### WarmupOptions Source: https://github.com/ionic-team/capacitor-docs/blob/main/docs/apis/local-llm.md Options for warming up the on-device LLM. ```APIDOC ## WarmupOptions Options for warming up the on-device LLM. ### Properties * **`sessionId`** (string) - Required - The session identifier for the warmup. This identifier will be associated with the warmed-up session, allowing you to use the same session for subsequent prompts. * **`promptPrefix`** (string) - Required - The prompt prefix to use for warming up the LLM. This text will be used to pre-initialize the model, reducing latency for subsequent prompts with similar prefixes. ``` -------------------------------- ### Add FirebaseFirestore Dependency to Capacitor iOS Plugin (Package.swift) Source: https://github.com/ionic-team/capacitor-docs/blob/main/docs/plugins/creating-plugins/ios-guide.md This example demonstrates adding `FirebaseFirestore` as a dependency for a Capacitor iOS plugin using Swift Package Manager. It includes dependencies for Capacitor and Firebase SDKs, specifying version constraints. ```swift let package = Package( // ... other configurations dependencies: [ .package(url: "https://github.com/ionic-team/capacitor-swift-pm.git", from: "7.0.0"), .package(url: "https://github.com/firebase/firebase-ios-sdk.git", from: "11.8.0") ], targets: [ .target( name: "FirebaseFirestorePlugin", dependencies: [ .product(name: "Capacitor", package: "capacitor-swift-pm"), .product(name: "Cordova", package: "capacitor-swift-pm"), .product(name: "FirebaseCore", package: "firebase-ios-sdk"), .product(name: "FirebaseFirestore", package: "firebase-ios-sdk") ], path: "ios/Plugin") ] // ... other configurations ) ``` -------------------------------- ### Capacitor Preferences API: Get JSON Object Source: https://github.com/ionic-team/capacitor-docs/blob/main/docs/main/guides/storage.md Illustrates retrieving and parsing a JSON object stored with the Capacitor Preferences API. The retrieved value needs to be parsed from a string back into a JavaScript object. This method is intended for small data sets. ```typescript import { Preferences } from '@capacitor/preferences'; // JSON "get" example async getObject() { const ret = await Preferences.get({ key: 'user' }); const user = JSON.parse(ret.value); } ``` -------------------------------- ### Open Android Project Source: https://github.com/ionic-team/capacitor-docs/blob/main/docs/main/guides/push-notifications-firebase.md Opens the generated Android project in Android Studio. ```bash npx cap open android ``` -------------------------------- ### Bridge Pattern Example in Swift (Capacitor Device Plugin) Source: https://github.com/ionic-team/capacitor-docs/blob/main/docs/plugins/tutorial/code-abstraction.md This Swift code snippet demonstrates the Bridge design pattern, separating the high-level logic of getting the language code from the platform-specific implementation. It takes a CAPPluginCall as input and resolves it with the language code. ```swift @objc func getLanguageCode(_ call: CAPPluginCall) { let code = implementation.getLanguageCode() call.resolve([ "value": code ]) } ``` -------------------------------- ### Update Gradle Property Assignment Syntax Source: https://github.com/ionic-team/capacitor-docs/blob/main/docs/main/updating/plugins/8-0.md This example highlights the change in Gradle property assignment syntax required when upgrading to Gradle 8. It shows the transition from the deprecated space-assignment syntax to the `=` operator for assigning values to properties, as detailed in the Gradle upgrade guide. ```diff The following properties commonly need to be updated from space-assignment to `=` assignment: ``` -------------------------------- ### Record and Play Video Source: https://github.com/ionic-team/capacitor-docs/blob/main/docs/apis/camera.md Record a video using the device's camera and optionally save it to the gallery. This example shows how to configure persistence, include metadata, and then play the recorded video. It includes error handling for both recording and playback. ```typescript import { Camera } from '@capacitor/camera'; const recordAndPlay = async () => { let videoUri: string | undefined; try { const result = await Camera.recordVideo({ saveToGallery: false, isPersistent: true, // keep the file available across app launches includeMetadata: true, }); videoUri = result.uri; console.log('Duration:', result.metadata?.duration); console.log('Saved to gallery:', result.saved); } catch (e) { const error = e as any; const message = error.code ? `[${error.code}] ${error.message}` : error.message; console.error('recordVideo failed:', message); return; } if (videoUri) { try { await Camera.playVideo({ uri: videoUri }); } catch (e) { const error = e as any; const message = error.code ? `[${error.code}] ${error.message}` : error.message; console.error('playVideo failed:', message); } } }; ``` -------------------------------- ### Present Native Android Screen (Intent with Result) in Java Source: https://github.com/ionic-team/capacitor-docs/blob/main/docs/plugins/creating-plugins/android-guide.md This Java code demonstrates how to launch a native Android Activity and receive a result back using `startActivityForResult`. It includes setting up an Intent, starting the activity, and defining a callback method (`@ActivityCallback`) to process the result. ```java @CapacitorPlugin() class ImagePicker extends Plugin { @PluginMethod() public void pickImage(PluginCall call) { Intent intent = new Intent(Intent.ACTION_PICK); intent.setType("image/*"); // Start the Activity for result using the name of the callback method startActivityForResult(call, intent, "pickImageResult"); } @ActivityCallback private void pickImageResult(PluginCall call, ActivityResult result) { if (call == null) { return; } // Do something with the result data } } ``` -------------------------------- ### Capacitor Filesystem API Examples (TypeScript) Source: https://github.com/ionic-team/capacitor-docs/blob/main/docs/apis/filesystem.md A collection of TypeScript examples demonstrating common file operations using the Capacitor Filesystem API. This includes writing, reading, and deleting files within specific directories, as well as handling files using full URIs and appending binary data. ```typescript import { Filesystem, Directory, Encoding } from "@capacitor/filesystem"; const writeSecretFile = async () => { await Filesystem.writeFile({ path: "secrets/text.txt", data: "This is a test", directory: Directory.Documents, encoding: Encoding.UTF8, }); }; const readSecretFile = async () => { const contents = await Filesystem.readFile({ path: "secrets/text.txt", directory: Directory.Documents, encoding: Encoding.UTF8, }); console.log("secrets:", contents); }; const deleteSecretFile = async () => { await Filesystem.deleteFile({ path: "secrets/text.txt", directory: Directory.Documents, }); }; const readFilePath = async () => { // Here's an example of reading a file with a full file path. Use this to // read binary data (base64 encoded) from plugins that return File URIs, such as // the Camera. const contents = await Filesystem.readFile({ path: "file:///var/mobile/Containers/Data/Application/22A433FD-D82D-4989-8BE6-9FC49DEA20BB/Documents/text.txt", }); console.log("data:", contents); }; const appendBinaryData = async () => { // Here's an example of appending binary data, which should be sent to the plugin // as base64 encoded, and without providing any `Encoding`. await Filesystem.appendFile({ path: "file.bin", directory: Directory.Cache, data: "VGhpcyBpcyBtZWFudCB0byByZXByZXNlbnQgYSBCaW5hcnkgRGF0YSBleGFtcGxlIGVuY29kZWQgaW4gQmFzZTY0Lg==" }); }; ``` -------------------------------- ### Complete AppDelegate.swift for Firebase Source: https://github.com/ionic-team/capacitor-docs/blob/main/docs/main/guides/push-notifications-firebase.md This is an example of a complete AppDelegate.swift file with Firebase integration and push notification handling. ```swift import UIKit import Capacitor import FirebaseCore import FirebaseMessaging @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. FirebaseApp.configure() return true } func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { Messaging.messaging().apnsToken = deviceToken Messaging.messaging().token(completion: { (token, error) in if let error = error { NotificationCenter.default.post(name: .capacitorDidFailToRegisterForRemoteNotifications, object: error) } else if let token = token { NotificationCenter.default.post(name: .capacitorDidRegisterForRemoteNotifications, object: token) } }) } func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) { NotificationCenter.default.post(name: .capacitorDidFailToRegisterForRemoteNotifications, object: error) } } ``` -------------------------------- ### Install and Link Ruby and OpenSSL for CocoaPods Source: https://github.com/ionic-team/capacitor-docs/blob/main/docs/main/ios/troubleshooting.md This sequence of commands updates OpenSSL and Ruby using Homebrew, which can resolve CocoaPods 'Failed to connect to GitHub' errors caused by outdated cryptographic protocols. It also ensures the PATH environment variable is correctly configured. ```bash brew install openssl brew upgrade openssl brew install ruby brew link --overwrite ruby ``` -------------------------------- ### Sync iOS Plugins with Capacitor CLI Source: https://github.com/ionic-team/capacitor-docs/blob/main/docs/main/ios/troubleshooting.md Ensures that Capacitor's native iOS project is synchronized with installed plugins. This command updates the native project files, including the Podfile, to reflect the current plugin dependencies. It's crucial for resolving 'Plugin Not Implemented' errors. ```bash npx cap sync ios ``` -------------------------------- ### Create New Capacitor App using npm Source: https://github.com/ionic-team/capacitor-docs/blob/main/docs/main/getting-started/installation.md Scaffolds a new Capacitor application in an empty directory using the `@capacitor/create-app` package. This command initializes a new project with the latest version of Capacitor. ```bash npm init @capacitor/app@latest ``` -------------------------------- ### show() Source: https://github.com/ionic-team/capacitor-docs/blob/main/docs/apis/keyboard.md Shows the keyboard. This method is only supported on Android. ```APIDOC ## show() ### Description Shows the keyboard. This method is only supported on Android. ### Method show() ### Returns Promise ### Since 1.0.0 ``` -------------------------------- ### Mocking Capacitor Storage in Jasmine Source: https://github.com/ionic-team/capacitor-docs/blob/main/docs/main/guides/mocking-plugins.md This snippet demonstrates how to mock the Capacitor Storage plugin within a Jasmine test. It shows how to spy on the 'get' method to return specific values for 'firstName' and 'lastName', and then asserts that the component properties are updated correctly. It also includes an example of spying on the 'clear' method when a button click occurs. ```TypeScript it("gets the first and last name", async () => { spyOn(Storage, 'get'); (Storage.get as any) .withArgs({ key: 'firstName' }) .and.returnValue(Promise.resolve({ value: 'Jason' })); (Storage.get as any) .withArgs({ key: 'lastName' }) .and.returnValue(Promise.resolve({ value: 'Jones' })); fixture.detectChanges(); await fixture.whenRenderingDone(); expect(component.firstName).toEqual('Jason'); expect(component.lastName).toEqual('Jones'); }); it('clears the storage', () => { spyOn(Storage, 'clear'); click(clear.nativeElement); fixture.detectChanges(); expect(Storage.clear).toHaveBeenCalledTimes(1); }); ``` -------------------------------- ### Full `home.page.ts` Implementation Source: https://github.com/ionic-team/capacitor-docs/blob/main/docs/main/guides/push-notifications-firebase.md Complete implementation of `home.page.ts` including component setup and push notification handling logic. ```typescript import { Component, OnInit } from '@angular/core'; import { ActionPerformed, PushNotificationSchema, PushNotifications, Token, } from '@capacitor/push-notifications'; @Component({ selector: 'app-home', templateUrl: 'home.page.html', styleUrls: ['home.page.scss'], }) export class HomePage implements OnInit { ngOnInit() { console.log('Initializing HomePage'); // Request permission to use push notifications // iOS will prompt user and return if they granted permission or not // Android will just grant without prompting PushNotifications.requestPermissions().then(result => { if (result.receive === 'granted') { // Register with Apple / Google to receive push via APNS/FCM PushNotifications.register(); } else { // Show some error } }); PushNotifications.addListener('registration', (token: Token) => { alert('Push registration success, token: ' + token.value); }); PushNotifications.addListener('registrationError', (error: any) => { alert('Error on registration: ' + JSON.stringify(error)); }); PushNotifications.addListener( 'pushNotificationReceived', (notification: PushNotificationSchema) => { alert('Push received: ' + JSON.stringify(notification)); }, ); PushNotifications.addListener( 'pushNotificationActionPerformed', (notification: ActionPerformed) => { alert('Push action performed: ' + JSON.stringify(notification)); }, ); } } ``` -------------------------------- ### Angular Example: Creating a Google Map Source: https://github.com/ionic-team/capacitor-docs/blob/main/docs/apis/google-maps.md This full Angular example demonstrates how to create a Google Map within an Angular component. It includes the necessary imports, component decorator with template and styles, and a method to initialize the map using the GoogleMap.create method. ```typescript import { GoogleMap } from '@capacitor/google-maps'; @Component({ template: ` `, styles: [ ` capacitor-google-map { display: inline-block; width: 275px; height: 400px; } `, ], }) export class MyMap { @ViewChild('map') mapRef: ElementRef; newMap: GoogleMap; async createMap() { this.newMap = await GoogleMap.create({ id: 'my-cool-map', element: this.mapRef.nativeElement, apiKey: environment.apiKey, config: { center: { lat: 33.6, lng: -117.9, }, zoom: 8, }, }); } } ``` -------------------------------- ### iOS edit-config Example for Info.plist Source: https://github.com/ionic-team/capacitor-docs/blob/main/docs/main/cordova/migrating-from-cordova-to-capacitor.md An example of an edit-config element in config.xml for iOS, which requires configuration in the Info.plist file. This specific example sets the NSCameraUsageDescription. ```xml Used to take photos ``` -------------------------------- ### Install Ionic CLI and Native Run Source: https://github.com/ionic-team/capacitor-docs/blob/main/docs/main/guides/live-reload.md Installs the Ionic CLI and `native-run` utility globally, which are necessary for using the `ionic cap run` command for live reloading. ```bash npm install -g @ionic/cli native-run ``` -------------------------------- ### App State and Info Methods Source: https://github.com/ionic-team/capacitor-docs/blob/main/docs/apis/app.md Methods for retrieving the current application state, launch URL, and language settings. ```APIDOC ## getState() ### Description Gets the current app state. ### Returns - **Promise** - The current application state. ## getLaunchUrl() ### Description Get the URL the app was launched with, if any. ### Returns - **Promise** - The launch URL if available. ## getAppLanguage() ### Description Get the app specific language locale code. ### Returns - **Promise** - The language locale code. ``` -------------------------------- ### Complete Podfile Configuration for Firebase Source: https://github.com/ionic-team/capacitor-docs/blob/main/docs/main/guides/push-notifications-firebase.md This is an example of a complete Podfile for a Capacitor project that includes Firebase Messaging. It sets up Capacitor pods and adds the FirebaseMessaging pod. ```ruby require_relative '../../node_modules/@capacitor/ios/scripts/pods_helpers' platform :ios, '14.0' use_frameworks! # workaround to avoid Xcode caching of Pods that requires # Product -> Clean Build Folder after new Cordova plugins installed # Requires CocoaPods 1.6 or newer install! 'cocoapods', :disable_input_output_paths => true def capacitor_pods pod 'Capacitor', :path => '../../node_modules/@capacitor/ios' pod 'CapacitorCordova', :path => '../../node_modules/@capacitor/ios' pod 'CapacitorApp', :path => '../../node_modules/@capacitor/app' pod 'CapacitorHaptics', :path => '../../node_modules/@capacitor/haptics' pod 'CapacitorKeyboard', :path => '../../node_modules/@capacitor/keyboard' pod 'CapacitorPushNotifications', :path => '../../node_modules/@capacitor/push-notifications' pod 'CapacitorStatusBar', :path => '../../node_modules/@capacitor/status-bar' end target 'App' do capacitor_pods # Add your Pods here pod 'FirebaseMessaging' end post_install do |installer| assertDeploymentTarget(installer) end ``` -------------------------------- ### Handling `CameraSource.Prompt` (or default) Source: https://github.com/ionic-team/capacitor-docs/blob/main/docs/apis/camera.md Explains how to handle the removal of `CameraSource.Prompt` by implementing a custom UI to choose between taking a photo or selecting from the gallery. ```APIDOC ## Handling CameraSource.Prompt (Deprecated) ### Description The `CameraSource.Prompt` option, which previously displayed a native prompt for the user to choose between the camera and gallery, has been removed. You should now implement your own UI (e.g., using `@capacitor/action-sheet`) to present these options to the user and then call either `Camera.takePhoto` or `Camera.chooseFromGallery` based on their selection. ### Request Example ```typescript // Before const photo = await Camera.getPhoto({ // source defaults to CameraSource.Prompt quality: 90, resultType: CameraResultType.Uri, }); // After: show your own UI to determine the source, then call the appropriate method // Example using a hypothetical action sheet: // ActionSheet.showActions({ // options: [ // { text: 'Take Photo', value: 'camera' }, // { text: 'Choose from Gallery', value: 'gallery' } // ] // }).then(async (result) => { // if (result.value === 'camera') { // const photoResult = await Camera.takePhoto({ quality: 90 }); // // use photoResult.webPath // } else if (result.value === 'gallery') { // const galleryResult = await Camera.chooseFromGallery({ quality: 90 }); // // use galleryResult.results[0].webPath // } // }); ``` ``` -------------------------------- ### Run Capacitor Builds with Environment Variables Source: https://github.com/ionic-team/capacitor-docs/blob/main/docs/main/guides/environment-specific-configurations.md Demonstrates how to prepend `NODE_ENV` to Capacitor CLI commands to build for specific environments. This example shows how to run `cap copy` and `cap run` for the QA environment. ```bash NODE_ENV=qa npx cap copy NODE_ENV=qa npx cap run ios #NODE_ENV=qa npx cap run android ```