### Configure Android and Java Environment Variables (Windows) Source: https://nativephp.com/docs/mobile/1/getting-started/environment-setup Sets environment variables for Android development on Windows, including ANDROID_HOME and updates the system PATH. This example assumes specific default installation paths for Android SDK and JDK (Java 17). ```shell set ANDROID_HOME=C:\Users\yourname\AppData\Local\Android\Sdk set PATH=%PATH%;%JAVA_HOME%\bin;%ANDROID_HOME%\platform-tools # This isn't required if JAVA_HOME is already set in the Windows Env Variables set JAVA_HOME=C:\Program Files\Microsoft\jdk-17.0.8.7-hotspot ``` -------------------------------- ### Install and Run NativePHP Mobile App Source: https://nativephp.com/docs/mobile/1/getting-started/quick-start These commands install the NativePHP mobile package into a new Laravel application, prepare the app for native compilation, and then run it on a mobile device. Ensure you have an active NativePHP license and your mobile development environment configured. ```bash composer require nativephp/mobile php artisan native:install php artisan native:run ``` -------------------------------- ### Install Xcode Command Line Tools Source: https://nativephp.com/docs/mobile/1/getting-started/environment-setup Installs the necessary command-line tools for Xcode development. Verifies the installation by printing the path to the command-line tools. ```shell xcode-select --install xcode-select -p ``` -------------------------------- ### Start NativePHP App with Artisan Command Source: https://nativephp.com/docs/mobile/1/getting-started/installation This command initiates the compilation and booting process for your NativePHP application on a selected device. Ensure your app runs in the browser first to address potential exceptions. ```shell php artisan native:run ``` -------------------------------- ### Install Homebrew Package Manager Source: https://nativephp.com/docs/mobile/1/getting-started/environment-setup Installs Homebrew, a package manager for macOS, which is used to install other development tools like CocoaPods. This script fetches and executes the Homebrew installation command. ```shell /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)" ``` -------------------------------- ### Install CocoaPods for iOS Development Source: https://nativephp.com/docs/mobile/1/getting-started/environment-setup Installs CocoaPods, a dependency manager for Swift and Objective-C, using Homebrew. It also includes a command to verify the CocoaPods installation by checking its version. ```shell brew install cocoapods pod --version ``` -------------------------------- ### Run NativePHP Installer - Shell Source: https://nativephp.com/docs/mobile/1/getting-started/installation This Artisan command initiates the NativePHP installation process within your Laravel application. It configures the project for iOS and Android development and may prompt you to install ICU-enabled PHP binaries if your application requires the `intl` PHP extension. ```shell php artisan native:install ``` -------------------------------- ### Install NativePHP Composer Package - Shell Source: https://nativephp.com/docs/mobile/1/getting-started/installation This shell command installs the NativePHP mobile package using Composer. After adding the repository to your `composer.json`, run this command in your project's root directory. You may be prompted for authentication using your license email and key. ```shell composer require nativephp/mobile ``` -------------------------------- ### Configure Android and Java Environment Variables (macOS) Source: https://nativephp.com/docs/mobile/1/getting-started/environment-setup Sets environment variables for Android development on macOS, including JAVA_HOME, ANDROID_HOME, and updates the system PATH to include necessary Android SDK and Java binaries. This assumes Java 17 is installed. ```shell # This isn't required if JAVA_HOME is already set in your environment variables (check using `printenv | grep JAVA_HOME`) export JAVA_HOME=$(/usr/libexec/java_home -v 17) export ANDROID_HOME=$HOME/Library/Android/sdk export PATH=$PATH:$JAVA_HOME/bin:$ANDROID_HOME/emulator:$ANDROID_HOME/tools:$ANDROID_HOME/tools/bin:$ANDROID_HOME/platform-tools ``` -------------------------------- ### Configure NativePHP Environment Variables - DotEnv Source: https://nativephp.com/docs/mobile/1/getting-started/installation These environment variables are essential for the NativePHP installation and application setup. `NATIVEPHP_APP_ID` defines a unique identifier for your application, `NATIVEPHP_APP_VERSION` sets the application version string, and `NATIVEPHP_APP_VERSION_CODE` provides a numerical version code. The `NATIVEPHP_DEVELOPMENT_TEAM` is optional but recommended for Apple development. ```dotenv NATIVEPHP_APP_ID=com.yourcompany.yourapp NATIVEPHP_APP_VERSION="DEBUG" NATIVEPHP_APP_VERSION_CODE="1" NATIVEPHP_DEVELOPMENT_TEAM={your team ID} ``` -------------------------------- ### Add Composer Repository - JSON Source: https://nativephp.com/docs/mobile/1/getting-started/installation This JSON snippet configures your `composer.json` file to include the NativePHP package repository. It specifies the repository type as 'composer' and provides the URL for the NativePHP package registry. ```json { "repositories": [ { "type": "composer", "url": "https://nativephp.composer.sh" } ] } ``` -------------------------------- ### Install NativePHP Dependencies (Shell) Source: https://nativephp.com/docs/mobile/1/concepts/ci-cd Installs NativePHP dependencies for mobile app development in CI/CD. Supports overwriting existing files and includes ICU support for specific features. The '--no-tty' flag is crucial for non-interactive environments. ```shell # Install Android platform, overwriting existing files php artisan native:install android --force --no-tty # Install with ICU support for Filament/intl features php artisan native:install android --force --with-icu # Install both platforms php artisan native:install both --force ``` -------------------------------- ### Setting App Version for Development with NativePHP Source: https://nativephp.com/docs/mobile/1/getting-started/configuration Demonstrates how to set the `NATIVEPHP_APP_VERSION` environment variable to `DEBUG`. This forces the application to always install the latest version of the code during development, ensuring quick iteration. Note that this can slow down app startup. ```dotenv NATIVEPHP_APP_VERSION=DEBUG ``` -------------------------------- ### Force NativePHP Reinstall - Shell Source: https://nativephp.com/docs/mobile/1/getting-started/installation This command forces a complete reinstallation and rebuild of the `nativephp` directory. It is necessary when upgrading the NativePHP package to ensure all native project files are updated. Use with caution as it will overwrite existing native project files. ```shell php artisan native:install --force ``` -------------------------------- ### Open Native Sharing Interface using PHP Source: https://nativephp.com/docs/mobile/1/apis/dialog Launches the device's native sharing interface, allowing users to share text and URLs through various installed applications. It includes a title for the share dialog. ```php use Native\Mobile\Facades\Dialog; Dialog::share( 'Check this out!', 'I found this amazing Laravel package for mobile development', 'https://nativephp.com' ); ``` -------------------------------- ### Seed Application Data with PHP Migration Source: https://nativephp.com/docs/mobile/1/concepts/databases An example of a PHP migration class that inserts initial data into the 'categories' table using Laravel's DB facade. ```php use Illuminate\Database\Migrations\Migration; use Illuminate\Support\Facades\DB; return new class extends Migration { public function up() { DB::table('categories')->insert([ ['name' => 'Work', 'color' => '#3B82F6'], ['name' => 'Personal', 'color' => '#10B981'], ]); } }; ``` -------------------------------- ### Get Device Info - PHP Source: https://nativephp.com/docs/mobile/1/apis/device Fetches comprehensive information about the device, operating system, and platform, returned as a JSON encoded string. This includes details like device name, model, platform, OS version, and memory usage. Requires the NativeMobileFacadesDevice namespace. ```php use Native\Mobile\Facades\Device; $deviceInfoJson = Device::getInfo(); $deviceInfo = json_decode($deviceInfoJson, true); ``` -------------------------------- ### Manage Location Permissions with NativePHP Geolocation Source: https://nativephp.com/docs/mobile/1/apis/geolocation Provides code examples for checking the current status of location permissions and requesting them from the user using the NativePHP Geolocation API. Permission status is communicated back through events. ```php use Native\Mobile\Facades\Geolocation; // Check current location permissions status Geolocation::checkPermissions(); // Request location permissions from the user Geolocation::requestPermissions(); ``` -------------------------------- ### Camera API - Get Photo Source: https://nativephp.com/docs/mobile/1/apis/camera Opens the camera interface to allow the user to take a photo. A `PhotoTaken` event will be fired upon successful capture. ```APIDOC ## POST /camera/getPhoto ### Description Opens the camera interface to take a photo. ### Method POST ### Endpoint /camera/getPhoto ### Parameters #### Query Parameters None #### Request Body None ### Request Example ```json { "message": "Initiate photo capture" } ``` ### Response #### Success Response (200) Indicates that the camera interface was successfully opened. The actual photo capture is handled via the `PhotoTaken` event. #### Response Example ```json { "status": "Camera interface opened" } ``` ``` -------------------------------- ### Device ID API Source: https://nativephp.com/docs/mobile/1/apis/device Get a unique identifier for the device. ```APIDOC ## GET /device/id ### Description Returns a unique identifier for the device. ### Method GET ### Endpoint /device/id ### Parameters #### Query Parameters None ### Request Example ```json { "example": "null" } ``` ### Response #### Success Response (200) - **id** (string) - A unique identifier for the device. #### Response Example ```json { "id": "a1b2c3d4-e5f6-7890-1234-567890abcdef" } ``` ``` -------------------------------- ### Configure Associated Domains for Deep Linking Source: https://nativephp.com/docs/mobile/1/concepts/deep-links Allows Universal Links (iOS) and App Links (Android) to open your NativePHP app directly. Configure the host in your .env file; the app will open instead of the browser if installed. Requires hosting verification files on your server. ```dotenv NATIVEPHP_DEEPLINK_HOST=example.net ``` -------------------------------- ### Get Device ID - PHP Source: https://nativephp.com/docs/mobile/1/apis/device Retrieves a unique identifier for the current device using the NativePHP Device facade. This method requires the NativeMobileFacadesDevice namespace to be imported. ```php use Native\Mobile\Facades\Device; $deviceId = Device::getId(); ``` -------------------------------- ### Configure Custom URL Scheme for Deep Linking Source: https://nativephp.com/docs/mobile/1/concepts/deep-links Enables your NativePHP mobile app to be opened via a custom URL scheme. Define a unique scheme in your .env file to handle inter-app data passing. This method requires the app to be installed. ```dotenv NATIVEPHP_DEEPLINK_SCHEME=myapp ``` -------------------------------- ### Handle Token Generated Event in Livewire (PHP) Source: https://nativephp.com/docs/mobile/1/concepts/push-notifications This Livewire component example in PHP shows how to listen for the `TokenGenerated` event. Upon receiving a new push notification token, it calls an external APIService to store the token, typically associating it with a user. ```php use App\Services\APIService; use Livewire\Attributes\On; use Native\Mobile\Facades\PushNotifications; use Native\Mobile\Events\PushNotification\TokenGenerated; class PushNotifications extends Component { #[On('native:' . TokenGenerated::class)] public function storePushToken(APIService $api, string $token) { $api->storePushToken($token); } } ``` -------------------------------- ### Get Battery Info - PHP Source: https://nativephp.com/docs/mobile/1/apis/device Retrieves the current battery status, including the battery level (as a percentage from 0 to 1) and whether the device is currently charging. The information is returned as a JSON encoded string. Requires the NativeMobileFacadesDevice namespace. ```php use Native\Mobile\Facades\Device; $batteryInfoJson = Device::getBatteryInfo(); $batteryInfo = json_decode($batteryInfoJson, true); ``` -------------------------------- ### Get Secure Value using SecureStorage in PHP Source: https://nativephp.com/docs/mobile/1/apis/secure-storage Retrieves a securely stored value using its associated key. If the key is found, the stored value is returned; otherwise, null is returned. This is useful for fetching sensitive information like authentication tokens. ```php $token = SecureStorage::get('api_token'); ``` -------------------------------- ### Get Device Location with NativePHP Geolocation Source: https://nativephp.com/docs/mobile/1/apis/geolocation Demonstrates how to retrieve the device's current geographic coordinates using the NativePHP Geolocation API. It shows how to request high-accuracy GPS positioning or a faster, less accurate network-based location. The results are typically handled through events. ```php use Native\Mobile\Facades\Geolocation; // Get location using network positioning (faster, less accurate) Geolocation::getCurrentPosition(); // Get location using GPS (slower, more accurate) Geolocation::getCurrentPosition(true); ``` -------------------------------- ### Package Signed Release with Command Line Options (Shell) Source: https://nativephp.com/docs/mobile/1/concepts/ci-cd Demonstrates packaging a signed Android release by providing all necessary signing details directly as command-line arguments. Useful for specific scripting scenarios but environment variables are generally preferred for security. ```shell php artisan native:package android \ --build-type=release \ --keystore=/path/to/keystore.jks \ --keystore-password=your-password \ --key-alias=your-alias \ --key-password=your-key-password \ --output=./artifacts \ --no-tty ``` -------------------------------- ### SecureStorage Facade Usage in PHP Source: https://nativephp.com/docs/mobile/1/apis/secure-storage Demonstrates the basic usage of the SecureStorage facade in PHP for interacting with the native device storage. This involves importing the facade and calling its methods. ```php use Native\Mobile\Facades\SecureStorage; ``` -------------------------------- ### Configure Android Signing Credentials (Bash) Source: https://nativephp.com/docs/mobile/1/concepts/ci-cd Sets up Android signing credentials using environment variables, a recommended practice for CI/CD security. These variables are used by NativePHP commands to sign application packages. ```bash # Android Signing export ANDROID_KEYSTORE_FILE="/path/to/keystore.jks" export ANDROID_KEYSTORE_PASSWORD="your-keystore-password" export ANDROID_KEY_ALIAS="your-key-alias" export ANDROID_KEY_PASSWORD="your-key-password" ``` -------------------------------- ### Import Haptics Facade Source: https://nativephp.com/docs/mobile/1/apis/haptics This snippet shows how to import the Haptics facade from the NativePHP Mobile library, which is necessary to use any of its methods. ```php use Native\Mobile\Facades\Haptics; ``` -------------------------------- ### Display Artisan Command Help Source: https://nativephp.com/docs/mobile/1/getting-started/development Shows the available arguments and options for the `native:run` Artisan command, allowing users to skip prompts by providing necessary values directly. This is useful for automating build processes or customizing command execution. ```shell php artisan native:run --help ``` -------------------------------- ### Control Flashlight with PHP Source: https://nativephp.com/docs/mobile/1/apis/system Toggles the device's flashlight on and off using the System facade. This method requires no arguments and returns void. Ensure the Native\Mobile\Facades\System namespace is imported. ```php use Native\Mobile\Facades\System; System::flashlight(); // Toggle flashlight state ``` -------------------------------- ### Package Signed Release with Environment Variables (Shell) Source: https://nativephp.com/docs/mobile/1/concepts/ci-cd Illustrates packaging a signed Android release using environment variables for sensitive credentials. This method is recommended for CI/CD pipelines to avoid hardcoding secrets directly in commands. ```shell # Set environment variables in CI export ANDROID_KEYSTORE_FILE="/path/to/keystore.jks" export ANDROID_KEYSTORE_PASSWORD="your-password" export ANDROID_KEY_ALIAS="your-alias" export ANDROID_KEY_PASSWORD="your-key-password" # Run packaging command php artisan native:package android --build-type=release --output=./artifacts --no-tty ``` -------------------------------- ### Build Mobile App Versions (Shell) Source: https://nativephp.com/docs/mobile/1/concepts/ci-cd Commands to build different versions of the mobile app for CI/CD. Supports debug, release, and app bundle formats, essential for development and production deployments. The '--no-tty' flag ensures compatibility with automated environments. ```shell # Build debug version (development) php artisan native:run android --build=debug --no-tty # Build release version (production) php artisan native:run android --build=release --no-tty # Build app bundle for Play Store php artisan native:run android --build=bundle --no-tty ``` -------------------------------- ### Initialize Camera Facade Source: https://nativephp.com/docs/mobile/1/apis/camera Imports the Camera facade for accessing camera functionalities. This is a prerequisite for using any camera-related methods. ```php use Native\Mobile\Facades\Camera; ``` -------------------------------- ### Run and Compile App (Shell) Source: https://nativephp.com/docs/mobile/1/getting-started/development Compile and run your NativePHP application for debugging. This command simplifies the build and execution process, eliminating the need for platform-specific tools. ```shell php artisan native:run --build=debug ``` -------------------------------- ### Frontend Event Handling with Livewire #[On()] Attribute Source: https://nativephp.com/docs/mobile/1/the-basics/events Demonstrates how to use Livewire's `#[On()]` attribute to listen for events broadcast from the native mobile application. Events are prefixed with `native:` followed by the event class name. ```php use Native\Mobile\Events\Camera\PhotoTaken; #[On('native:'.PhotoTaken::class)] public function handlePhoto(string $path) { // Handle captured photo } ``` -------------------------------- ### Compile Frontend Assets with NPM Source: https://nativephp.com/docs/mobile/1/the-basics/assets This command compiles frontend assets using NPM, ensuring the latest styles and JavaScript are included in the native application build. It should be run before `php artisan native:run`. ```bash npm run build ``` -------------------------------- ### Device Information API Source: https://nativephp.com/docs/mobile/1/apis/device Retrieve detailed information about the device, including its model, platform, OS version, and memory usage. ```APIDOC ## GET /device ### Description Retrieves information about the underlying device, OS, and platform. ### Method GET ### Endpoint /device ### Parameters #### Query Parameters None ### Request Example ```json { "example": "null" } ``` ### Response #### Success Response (200) - **name** (string) - The name of the device. - **model** (string) - The device model. - **platform** ('ios' | 'android') - The device platform. - **operatingSystem** (string) - The operating system of the device. - **osVersion** (string) - The version of the device OS. - **iOSVersion** (number) - The iOS version number (only on iOS). - **androidSDKVersion** (number) - The Android SDK version number (only on Android). - **manufacturer** (string) - The manufacturer of the device. - **isVirtual** (boolean) - Whether the app is running in a simulator/emulator. - **memUsed** (number) - Approximate memory used by the current app, in bytes. - **webViewVersion** (string) - The web view browser version. #### Response Example ```json { "name": "John's iPhone", "model": "iPhone13,4", "platform": "ios", "operatingSystem": "iOS", "osVersion": "16.3.1", "iOSVersion": 160301, "androidSDKVersion": null, "manufacturer": "Apple", "isVirtual": false, "memUsed": 104857600, "webViewVersion": "16.0.0" } ``` ``` -------------------------------- ### Package Signed Releases (Shell) Source: https://nativephp.com/docs/mobile/1/concepts/ci-cd Packages signed mobile app releases for distribution using CI/CD. Supports both APK and App Bundle formats for various distribution channels. Utilizes environment variables for secure handling of signing credentials. ```shell # Package signed APK using environment variables php artisan native:package android --build-type=release --output=/artifacts --no-tty # Package signed App Bundle for Play Store php artisan native:package android --build-type=bundle --output=/artifacts --no-tty ``` -------------------------------- ### Open Project in IDE (Shell) Source: https://nativephp.com/docs/mobile/1/getting-started/development Open the native project in its respective IDE (Xcode or Android Studio) for advanced development workflows. This command is useful for developers familiar with native IDEs. ```shell php artisan native:open ``` -------------------------------- ### Build Frontend for iOS (Shell) Source: https://nativephp.com/docs/mobile/1/getting-started/development Compile frontend assets with a specific mode for iOS builds. This command should be run before compiling the native app for iOS. ```shell npm run build -- --mode=ios ``` -------------------------------- ### Prompt for Biometric Authentication (PHP) Source: https://nativephp.com/docs/mobile/1/apis/biometrics This snippet demonstrates how to use the Biometrics facade to prompt the user for biometric authentication. It requires the Native\Mobile\Facades\Biometrics namespace. ```php use Native\Mobile\Facades\Biometrics; Biometrics::promptForBiometricID(); ``` -------------------------------- ### Synchronous API Calls in NativePHP Mobile Source: https://nativephp.com/docs/mobile/1/the-basics/events Demonstrates the usage of synchronous API calls that execute immediately in NativePHP Mobile. These methods do not require event listeners as they return results directly. ```php Haptics::vibrate(); System::flashlight(); Dialog::toast('Hello!'); ``` -------------------------------- ### Environment Variables for NativePHP Mobile Source: https://nativephp.com/docs/mobile/1/getting-started/configuration Lists the environment variables that can be used to configure NativePHP Mobile. These variables control aspects like app version, ID, deep linking, and build paths. They are typically set in the `.env` file. ```dotenv NATIVEPHP_APP_VERSION NATIVEPHP_APP_VERSION_CODE NATIVEPHP_APP_ID NATIVEPHP_DEEPLINK_SCHEME NATIVEPHP_DEEPLINK_HOST NATIVEPHP_APP_AUTHOR NATIVEPHP_GRADLE_PATH NATIVEPHP_ANDROID_SDK_LOCATION ``` -------------------------------- ### Create Seed Migration with Artisan Source: https://nativephp.com/docs/mobile/1/concepts/databases Generates a new migration file using the Artisan command-line tool, suitable for seeding application data. ```shell php artisan make:migration seed_app_settings ``` -------------------------------- ### Dialog Share API Source: https://nativephp.com/docs/mobile/1/apis/dialog Opens the native sharing interface for sharing content. ```APIDOC ## Dialog Share API ### Description Opens the native sharing interface. ### Method ```php Dialog::share() ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **title** (string) - Required - The share dialog title - **text** (string) - Required - Text content to share - **url** (string) - Required - URL to share ### Request Example ```php use Native\Mobile\Facades\Dialog; Dialog::share( 'Check this out!', 'I found this amazing Laravel package for mobile development', 'https://nativephp.com' ); ``` ### Response #### Success Response (N/A) This method does not return a direct value upon execution, but triggers a native UI element. #### Response Example N/A ``` -------------------------------- ### Camera API - Pick Images Source: https://nativephp.com/docs/mobile/1/apis/camera Opens the device's gallery or photo picker to allow the user to select existing images or videos. A `MediaSelected` event will be fired upon selection. ```APIDOC ## POST /camera/pickImages ### Description Opens the gallery/photo picker to select existing images or videos. ### Method POST ### Endpoint /camera/pickImages ### Parameters #### Query Parameters None #### Request Body - **media_type** (string) - Optional - Type of media to pick. Allowed values: `'all'`, `'images'`, `'videos'`. Defaults to `'all'`. - **multiple** (bool) - Optional - Allow multiple selection. Defaults to `false`. ### Request Example ```json { "media_type": "images", "multiple": true } ``` ### Response #### Success Response (200) Indicates that the gallery picker was successfully opened. The selected media details are provided via the `MediaSelected` event. #### Response Example ```json { "status": "Gallery picker opened" } ``` ``` -------------------------------- ### Backend Event Handling with Laravel Listeners Source: https://nativephp.com/docs/mobile/1/the-basics/events Illustrates how to handle events on the PHP backend using standard Laravel event listeners. This allows your Laravel application to react to events originating from the native mobile app. ```php use App\Services\APIService; use Native\Mobile\Events\Camera\PhotoTaken; class UpdateAvatar { public function __construct(private APIService $api) {} public function handle(PhotoTaken $event): void { $imageData = base64_encode( file_get_contents($event->path) ); $this->api->updateAvatar($imageData); } } ``` -------------------------------- ### Set Release Version and Build Code (Dotenv) Source: https://nativephp.com/docs/mobile/1/getting-started/development Configure environment variables to define the application's version number and build code for release. This is crucial for managing app updates and tracking releases. ```dotenv NATIVEPHP_APP_VERSION=1.2.3 NATIVEPHP_APP_VERSION_CODE=48 ``` -------------------------------- ### Create Release Build with Artisan Source: https://nativephp.com/docs/mobile/1/getting-started/development Executes a release build for the NativePHP application. This process optimizes the app by removing debugging code and unnecessary features, reducing size and improving performance. It is recommended to test this build on a real device before submission. ```shell php artisan native:run --build=release ``` -------------------------------- ### Use PushNotifications Facade - PHP Source: https://nativephp.com/docs/mobile/1/apis/push-notifications Imports the PushNotifications facade from the NativePHP Mobile library, essential for interacting with push notification functionalities. ```php use Native\Mobile\Facades\PushNotifications; ``` -------------------------------- ### Camera API - Events Source: https://nativephp.com/docs/mobile/1/apis/camera Handles events related to camera capture and media selection. ```APIDOC ## Events ### `PhotoTaken` Fired when a photo is taken with the camera. **Payload:** `string $path` - File path to the captured photo ```php use LivewireAttributes\On; use Native\Mobile\Events\Camera\PhotoTaken; #[On('native:'.PhotoTaken::class)] public function handlePhotoTaken(string $path) { // Process the captured photo $this->processPhoto($path); } ``` ### `MediaSelected` Fired when media is selected from the gallery. **Payload:** `array $media` - Array of selected media items. The actual structure of `$media` depends on the parameters passed to `pickImages` and the platform. Typically includes file paths and potentially other metadata. ```php use Livewire\Attributes\On; use Native\Mobile\Events\Gallery\MediaSelected; #[On('native:'.MediaSelected::class)] public function handleMediaSelected($success, $files, $count) { // $success (bool): Indicates if the selection was successful. // $files (array): An array of file paths for the selected media. // $count (int): The number of selected media items. if ($success) { foreach ($files as $file) { // Process each selected media item $this->processMedia($file); } } } ``` ``` -------------------------------- ### SecureStorage API Source: https://nativephp.com/docs/mobile/1/apis/secure-storage The SecureStorage API provides methods to securely store, retrieve, and delete data using the device's native keychain (iOS) or keystore (Android). ```APIDOC ## SecureStorage API ### Description The SecureStorage API provides secure storage using the device's native keychain (iOS) or keystore (Android). It's ideal for storing sensitive data like tokens, passwords, and user credentials. ## Methods ### `set()` Stores a secure value in the native keychain or keystore. ### Method POST ### Endpoint `/secure-storage/set` ### Parameters #### Request Body - **key** (string) - Required - The key to store the value under - **value** (string|null) - Required - The value to store securely ### Request Example ```json { "key": "api_token", "value": "abc123xyz" } ``` ### Response #### Success Response (200) - **success** (boolean) - `true` if successfully stored, `false` otherwise #### Response Example ```json { "success": true } ``` ### `get()` Retrieves a secure value from the native keychain or keystore. ### Method GET ### Endpoint `/secure-storage/get` ### Parameters #### Query Parameters - **key** (string) - Required - The key to retrieve the value for ### Request Example `/secure-storage/get?key=api_token` ### Response #### Success Response (200) - **value** (string|null) - The stored value or `null` if not found #### Response Example ```json { "value": "abc123xyz" } ``` ### `delete()` Deletes a secure value from the native keychain or keystore. ### Method DELETE ### Endpoint `/secure-storage/delete` ### Parameters #### Query Parameters - **key** (string) - Required - The key to delete the value for ### Request Example `/secure-storage/delete?key=api_token` ### Response #### Success Response (200) - **success** (boolean) - `true` if successfully deleted, `false` otherwise #### Response Example ```json { "success": true } ``` ``` -------------------------------- ### Composer Version Constraint for NativePHP Mobile Source: https://nativephp.com/docs/mobile/1/getting-started/versioning This JSON snippet demonstrates how to specify a version constraint for the nativephp/mobile package in your composer.json file. It uses the tilde range operator to allow for automatic patch updates while maintaining control over minor version upgrades. This ensures you receive bug fixes and minor improvements without introducing breaking changes. ```json { "require": { "nativephp/mobile": "~1.1.0" } } ``` -------------------------------- ### Asynchronous API Calls in NativePHP Mobile Source: https://nativephp.com/docs/mobile/1/the-basics/events Illustrates asynchronous API calls in NativePHP Mobile that trigger operations and fire events upon completion. These methods return immediately, allowing PHP execution to continue while native operations proceed. ```php // These trigger operations and fire events when complete Camera::getPhoto(); // → PhotoTaken event Biometrics::promptForBiometricID(); // → Completed event PushNotifications::enrollForPushNotifications(); // → TokenGenerated event ``` -------------------------------- ### Geolocation API Endpoints Source: https://nativephp.com/docs/mobile/1/apis/geolocation Methods for interacting with the device's geolocation services. ```APIDOC ## Geolocation API ### Description This API provides access to the device's GPS and location services to determine the user's current position. ### Methods #### `getCurrentPosition()` Gets the current GPS location of the device. - **Parameters**: - `fineAccuracy` (bool) - Optional - Whether to use high accuracy mode (GPS vs network) (default: `false`) - **Returns**: Location data via events. #### `checkPermissions()` Checks the current location permissions status. - **Returns**: Permission status via events. #### `requestPermissions()` Requests location permissions from the user. - **Returns**: Permission status after request via events. ### Request Example ```php use Native\Mobile\Facades\Geolocation; // Get location using network positioning (faster, less accurate) Geolocation::getCurrentPosition(); // Get location using GPS (slower, more accurate) Geolocation::getCurrentPosition(true); // Check permissions Geolocation::checkPermissions(); // Request permissions Geolocation::requestPermissions(); ``` ### Events #### `LocationReceived` Fired when location data is requested (success or failure). - **Event Parameters**: - `success` (bool) - Whether location was successfully retrieved - `latitude` (float) - Latitude coordinate (when successful) - `longitude` (float) - Longitude coordinate (when successful) - `accuracy` (float) - Accuracy in meters (when successful) - `timestamp` (int) - Unix timestamp of location fix - `provider` (string) - Location provider used (GPS, network, etc.) - `error` (string) - Error message (when unsuccessful) #### `PermissionStatusReceived` Fired when permission status is checked. - **Event Parameters**: - `location` (string) - Overall location permission status - `coarseLocation` (string) - Coarse location permission status - `fineLocation` (string) - Fine location permission status - **Permission Values**: - `'granted'` - Permission is granted - `'denied'` - Permission is denied - `'not_determined'` - Permission not yet requested #### `PermissionRequestResult` Fired when a permission request completes. - **Event Parameters**: - `location` (string) - Overall location permission result - `coarseLocation` (string) - Coarse location permission result - `fineLocation` (string) - Fine location permission result - `message` (string) - Optional message (for permanently denied) - `needsSettings` (bool) - Whether user needs to go to Settings - **Special Values**: - `'permanently_denied'` - User has permanently denied permission ### Response Example ```json { "event": "LocationReceived", "data": { "success": true, "latitude": 34.0522, "longitude": -118.2437, "accuracy": 10.5, "timestamp": 1678886400, "provider": "gps" } } { "event": "PermissionStatusReceived", "data": { "location": "granted", "coarseLocation": "granted", "fineLocation": "granted" } } { "event": "PermissionRequestResult", "data": { "location": "granted", "coarseLocation": "granted", "fineLocation": "granted", "message": null, "needsSettings": false } } ``` ``` -------------------------------- ### Pick Images from Gallery Source: https://nativephp.com/docs/mobile/1/apis/camera Uses the `pickImages()` method to open the device's gallery or photo picker. It allows specifying media type and whether multiple selections are permitted. Returns true if the picker was successfully opened. ```php // Pick a single image Camera::pickImages('images', false); // Pick multiple images Camera::pickImages('images', true); // Pick any media type Camera::pickImages('all', true); ``` -------------------------------- ### Frontend Event Handling with Native.on() in Blade Source: https://nativephp.com/docs/mobile/1/the-basics/events Shows how to register an event listener directly in JavaScript using the `Native.on()` helper within a Blade template. This is used to react to events broadcast from the native mobile application. ```blade @@use(Native\Mobile\Events\Alert\ButtonPressed) ``` -------------------------------- ### Configure Hot Reloading Paths (PHP) Source: https://nativephp.com/docs/mobile/1/getting-started/development Specify which directories and files NativePHP should watch for changes to trigger hot reloading. Ensure the 'public' directory is included for asset changes to be detected. ```php 'hot_reload' => [ 'watch_paths' => [ 'app', 'routes', 'config', 'database', 'public' ] ] ``` -------------------------------- ### Patch Inertia for iOS (Shell) Source: https://nativephp.com/docs/mobile/1/getting-started/development Apply a patch to the Axios package to ensure Inertia.js functions correctly on iOS builds. This command backs up the existing vite.config.js and replaces it with a patched version. ```shell php artisan native:patch-inertia ``` -------------------------------- ### Push Notifications API Source: https://nativephp.com/docs/mobile/1/apis/push-notifications This section details the methods available for managing push notifications, including enrolling devices and retrieving the FCM token. ```APIDOC ## Push Notifications API ### Description The PushNotifications API handles device registration for Firebase Cloud Messaging to receive push notifications. ### Methods #### `enrollForPushNotifications()` ##### Description Requests permission and enrolls the device for push notifications. ##### Method POST ##### Endpoint `/push-notifications/enroll ##### Parameters *No parameters available for this method.* ##### Request Example ```json { "message": "Requesting push notification permission." } ``` ##### Response *No specific response body is defined, as this method primarily triggers system permission dialogs.* #### `getPushNotificationsToken()` ##### Description Retrieves the current FCM token for this device. ##### Method GET ##### Endpoint `/push-notifications/token ##### Parameters *No parameters available for this method.* ##### Request Example ```json { "message": "Requesting the current FCM token." } ``` ##### Response * **token** (string|null) - The FCM token, or `null` if not available ##### Response Example ```json { "token": "your_fcm_token_here" } ``` ### Events #### `TokenGenerated` Fired when a push notification token is successfully generated. **Payload:** `string $token` - The FCM token for this device ```php use Livewire\Attributes\On; use Native\Mobile\Events\PushNotification\TokenGenerated; #[On('native:'.TokenGenerated::class)] public function handlePushToken(string $token) { // Send token to your backend $this->sendTokenToServer($token); } ``` ``` -------------------------------- ### Take Photo with Camera Source: https://nativephp.com/docs/mobile/1/apis/camera Utilizes the `getPhoto()` method from the Camera facade to open the device's camera interface. This method initiates the process of capturing a new photograph. ```php Camera::getPhoto(); ``` -------------------------------- ### Configure Vite for Hot Reloading (JavaScript) Source: https://nativephp.com/docs/mobile/1/getting-started/development Update your Vite configuration to enable hot module replacement (HMR) and set the correct host for development. This ensures seamless integration with NativePHP's hot reloading. ```javascript server: { port: 5173, cors: true, hmr: { host: '127.0.0.1', }, } ``` -------------------------------- ### Trigger Device Vibration Source: https://nativephp.com/docs/mobile/1/apis/haptics This snippet demonstrates how to trigger a device's vibration using the Haptics facade. This is useful for providing tactile feedback for user interactions such as button presses or important notifications. ```php Haptics::vibrate(); ``` -------------------------------- ### Handle Media Selected Event Source: https://nativephp.com/docs/mobile/1/apis/camera Responds to the `MediaSelected` event, triggered when media items are chosen from the gallery. The event provides details about the selection, including success status, files, and count. ```php use Livewire\Attributes\On; use Native\Mobile\Events\Gallery\MediaSelected; #[On('native:'.MediaSelected::class)] public function handleMediaSelected($success, $files, $count) { foreach ($files as $file) { // Process each selected media item $this->processMedia($file); } } ``` -------------------------------- ### Open URL for Authentication Flow (PHP) Source: https://nativephp.com/docs/mobile/1/apis/browser Launches a specialized authentication browser for OAuth flows, automatically handling redirects to the `nativephp://` scheme. This method enhances security by isolating authentication sessions and simplifying callback handling. ```php use Native\Mobile\Facades\Browser; Browser::auth('https://provider.com/oauth/authorize?client_id=123&redirect_uri=nativephp://127.0.0.1/auth/callback'); ``` -------------------------------- ### Encrypt and Decrypt Data with NativePHP SecureStorage Source: https://nativephp.com/docs/mobile/1/concepts/security This snippet demonstrates how to generate a unique encryption key for each user, store it securely using NativePHP's SecureStorage facade, and then use this key to encrypt and decrypt data before storing it in the application's storage. It ensures that sensitive data is protected even when the application is distributed. ```php use Illuminate\Encryption\Encrypter; use Illuminate\Support\Facades\Storage; use Native\Mobile\Facades\SecureStorage; function generateRandomKey() { return base64_encode( Encrypter::generateKey(config('app.cipher')) ); } $encryptionKey = SecureStorage::get('encryption_key'); if (! $encryptionKey) { SecureStorage::set('encryption_key', $encryptionKey = generateRandomKey()); } $mobileEncrypter = new Encrypter($encryptionKey); $encryptedContents = $mobileEncrypter->encrypt( $request->file('super_private_file') ); Storage::put('my_secure_file.pdf', $encryptedContents); // To decrypt later: $decryptedContents = $mobileEncrypter->decrypt( Storage::get('my_secure_file.pdf') ); ``` -------------------------------- ### Dialog Alert API Source: https://nativephp.com/docs/mobile/1/apis/dialog Displays a native alert dialog with customizable title, message, and buttons. ```APIDOC ## Dialog Alert API ### Description Displays a native alert dialog with customizable buttons. ### Method ```php Dialog::alert() ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **title** (string) - Required - The alert title - **message** (string) - Required - The alert message - **buttons** (array) - Required - Array of button labels (max 3 buttons) - Button Positioning: - 1 button - Positive (OK/Confirm) - 2 buttons - Negative (Cancel) + Positive (OK/Confirm) - 3 buttons - Negative (Cancel) + Neutral (Maybe) + Positive (OK/Confirm) ### Request Example ```php use Native\Mobile\Facades\Dialog; Dialog::alert( 'Confirm Action', 'Are you sure you want to delete this item?', ['Cancel', 'Delete'] ); ``` ### Response #### Success Response (N/A) This method does not return a direct value upon execution, but triggers a native UI element. #### Response Example N/A ``` -------------------------------- ### Set Secure Value using SecureStorage in PHP Source: https://nativephp.com/docs/mobile/1/apis/secure-storage Stores a value securely using the SecureStorage API. This method takes a key and a value, persisting it in the device's native secure storage. It returns a boolean indicating success or failure. ```php SecureStorage::set('api_token', 'abc123xyz'); ``` -------------------------------- ### Battery Information API Source: https://nativephp.com/docs/mobile/1/apis/device Retrieve information about the device's battery status, including charge level and charging state. ```APIDOC ## GET /device/battery ### Description Returns information about the device's battery. ### Method GET ### Endpoint /device/battery ### Parameters #### Query Parameters None ### Request Example ```json { "example": "null" } ``` ### Response #### Success Response (200) - **batteryLevel** (number) - A percentage (0 to 1) indicating how much the battery is charged. - **isCharging** (boolean) - Whether the device is charging. #### Response Example ```json { "batteryLevel": 0.85, "isCharging": true } ``` ``` -------------------------------- ### Display Alert Dialog using PHP Source: https://nativephp.com/docs/mobile/1/apis/dialog Shows a native alert dialog with a title, message, and customizable buttons. The number and type of buttons are determined by the provided array, following specific positioning guidelines. ```php use Native\Mobile\Facades\Dialog; Dialog::alert( 'Confirm Action', 'Are you sure you want to delete this item?', ['Cancel', 'Delete'] ); ``` -------------------------------- ### Handle Biometric Authentication Completion Event (PHP) Source: https://nativephp.com/docs/mobile/1/apis/biometrics This code shows how to listen for the Biometric\Completed event using Livewire's #[On] attribute. The handler receives a boolean indicating authentication success and allows for conditional logic based on the outcome. ```php use Livewire\Attributes\On; use Native\Mobile\Events\Biometric\Completed; #[On('native:' . Completed::class)] public function handleBiometricAuth(bool $success) { if ($success) { // User authenticated successfully $this->unlockSecureFeature(); } else { // Authentication failed $this->showErrorMessage(); } } ``` -------------------------------- ### Enabling Biometric Permission in NativePHP Configuration Source: https://nativephp.com/docs/mobile/1/getting-started/configuration Shows how to enable the biometric permission within the `config/nativephp.php` file. This allows your application to use fingerprint or face-recognition hardware for security. Other permissions can be enabled similarly by changing their boolean value to `true`. ```php 'permissions' => [ 'biometric' => true, ], ``` -------------------------------- ### Check Mobile Platform (PHP) Source: https://nativephp.com/docs/mobile/1/getting-started/development Determine if the application is running on iOS or Android using helper facades. This is useful for implementing platform-specific UI or functionality. ```php use Native\Mobile\Facades\System; System::isIos() // -> `true` on iOS System::isAndroid() // -> `true` on Android ``` -------------------------------- ### Handle Permission Status Received Event in Livewire Source: https://nativephp.com/docs/mobile/1/apis/geolocation Shows how to handle the `PermissionStatusReceived` event in a Livewire component, which is triggered when location permissions are checked via the NativePHP Geolocation API. It allows you to access the status of overall, coarse, and fine location permissions. ```php use Livewire\Attributes\On; use Native\Mobile\Events\Geolocation\PermissionStatusReceived; #[On('native:' . PermissionStatusReceived::class)] public function handlePermissionStatus($location, $coarseLocation, $fineLocation) { // Use $location, $coarseLocation, $fineLocation to determine permission status // Possible values: 'granted', 'denied', 'not_determined' } ``` -------------------------------- ### Handle Permission Request Result Event in Livewire Source: https://nativephp.com/docs/mobile/1/apis/geolocation Demonstrates handling the `PermissionRequestResult` event in Livewire, which is fired after the user responds to a location permission request. This event provides the final permission status and indicates if the user needs to be directed to device settings, especially for permanently denied permissions. ```php use Livewire\Attributes\On; use Native\Mobile\Events\Geolocation\PermissionRequestResult; #[On('native:' . PermissionRequestResult::class)] public function handlePermissionRequest($location, $coarseLocation, $fineLocation, $message = null, $needsSettings = null) { if ($location === 'permanently_denied') { $this->error = 'Location permission permanently denied. Please enable in Settings.'; } elseif ($coarseLocation === 'granted' || $fineLocation === 'granted') { $this->getCurrentLocation(); // Example: proceed if granted } else { $this->error = 'Location permission is required for this feature.'; } } ``` -------------------------------- ### Handle Photo Taken Event Source: https://nativephp.com/docs/mobile/1/apis/camera Listens for the `PhotoTaken` event, which is fired after a photo is successfully captured by the camera. The event payload contains the file path of the taken photo. ```php use Livewire\Attributes\On; use Native\Mobile\Events\Camera\PhotoTaken; #[On('native:'.PhotoTaken::class)] public function handlePhotoTaken(string $path) { // Process the captured photo $this->processPhoto($path); } ``` -------------------------------- ### Detect iOS Device with PHP Source: https://nativephp.com/docs/mobile/1/apis/system Checks if the current device is running the iOS operating system. This method returns a boolean value: true if the device is iOS, false otherwise. It requires the System facade to be imported. ```php use Native\Mobile\Facades\System; if (System::isIos()) { // Code to execute on iOS } ```