CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-ionic-native

Native plugin wrappers for Cordova and Ionic with TypeScript, ES6+, Promise and Observable support

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

storage-files.mddocs/

Storage & File Management

File system operations, database access, and secure storage solutions for mobile app data persistence and management.

Capabilities

File System Operations

Comprehensive file system access for creating, reading, writing, and managing files and directories across platform-specific locations.

/**
 * File system entry base interface
 */
interface Entry {
  /** Whether this entry is a file */
  isFile: boolean;
  /** Whether this entry is a directory */
  isDirectory: boolean;
  /** Name of this entry, excluding the path leading to it */
  name: string;
  /** Full absolute path from the root to this entry */
  fullPath: string;
}

/**
 * File entry interface extending base Entry
 */
interface FileEntry extends Entry {
  /**
   * Get File object for reading file properties
   * @param successCallback Success callback with File object
   * @param errorCallback Error callback with FileError
   */
  file(successCallback: (file: File) => void, errorCallback?: (error: FileError) => void): void;
  
  /**
   * Create FileWriter for writing to the file
   * @param successCallback Success callback with FileWriter
   * @param errorCallback Error callback with FileError
   */
  createWriter(successCallback: (writer: FileWriter) => void, errorCallback?: (error: FileError) => void): void;
}

/**
 * Directory entry interface extending base Entry
 */
interface DirectoryEntry extends Entry {
  /**
   * Create directory reader for listing contents
   * @returns DirectoryReader instance
   */
  createReader(): DirectoryReader;
  
  /**
   * Get or create a file within this directory
   * @param path Relative path to the file
   * @param options Flags for file operations
   * @param successCallback Success callback with FileEntry
   * @param errorCallback Error callback with FileError
   */
  getFile(path: string, options?: Flags, successCallback?: (entry: FileEntry) => void, errorCallback?: (error: FileError) => void): void;
  
  /**
   * Get or create a directory within this directory
   * @param path Relative path to the directory
   * @param options Flags for directory operations
   * @param successCallback Success callback with DirectoryEntry
   * @param errorCallback Error callback with FileError
   */
  getDirectory(path: string, options?: Flags, successCallback?: (entry: DirectoryEntry) => void, errorCallback?: (error: FileError) => void): void;
}

/**
 * File operation flags
 */
interface Flags {
  /** Create file/directory if it doesn't exist */
  create?: boolean;
  /** Fail if file/directory already exists (only with create: true) */
  exclusive?: boolean;
}

/**
 * File writing options
 */
interface IWriteOptions {
  /** Replace existing file content (default: true) */
  replace?: boolean;
  /** Append to existing file content */
  append?: boolean;
  /** Truncate file before writing */
  truncate?: number;
}

/**
 * File removal result
 */
interface RemoveResult {
  /** Whether removal was successful */
  success: boolean;
  /** Entry that was removed */
  fileRemoved: Entry;
}

/**
 * File class providing comprehensive file system operations
 */
class File {
  /** Read-only directory where the application is installed */
  static applicationDirectory: string;
  
  /** Directory where to store app-specific data files */
  static dataDirectory: string;
  
  /** Directory where to store cached data files */
  static cacheDirectory: string;
  
  /** Directory where to store external app-specific data files */
  static externalApplicationStorageDirectory: string;
  
  /** Directory where to store external data files */
  static externalDataDirectory: string;
  
  /** Directory where to store external cached data files */
  static externalCacheDirectory: string;
  
  /** External storage (SD card) root directory */
  static externalRootDirectory: string;
  
  /** Temporary file directory */
  static tempDirectory: string;
  
  /** Synced data directory (iOS) */
  static syncedDataDirectory: string;
  
  /** Documents directory */
  static documentsDirectory: string;
  
  /** Shared directory */
  static sharedDirectory: string;

  /**
   * Get available free disk space
   * @returns Promise resolving to free space in bytes
   */
  static getFreeDiskSpace(): Promise<number>;

  /**
   * Check if directory exists
   * @param path Directory path
   * @param dir Directory name
   * @returns Promise resolving to boolean indicating existence
   */
  static checkDir(path: string, dir: string): Promise<boolean>;

  /**
   * Create directory
   * @param path Parent directory path
   * @param dirName Directory name to create
   * @param replace Whether to replace existing directory
   * @returns Promise resolving to DirectoryEntry
   */
  static createDir(path: string, dirName: string, replace: boolean): Promise<DirectoryEntry>;

  /**
   * Remove directory
   * @param path Directory path
   * @param dirName Directory name to remove
   * @returns Promise resolving to RemoveResult
   */
  static removeDir(path: string, dirName: string): Promise<RemoveResult>;

  /**
   * Move directory to new location
   * @param path Source directory path
   * @param dirName Source directory name
   * @param newPath Destination directory path
   * @param newDirName New directory name
   * @returns Promise resolving to DirectoryEntry or Entry
   */
  static moveDir(path: string, dirName: string, newPath: string, newDirName: string): Promise<DirectoryEntry | Entry>;

  /**
   * Copy directory to new location
   * @param path Source directory path
   * @param dirName Source directory name
   * @param newPath Destination directory path
   * @param newDirName New directory name
   * @returns Promise resolving to Entry
   */
  static copyDir(path: string, dirName: string, newPath: string, newDirName: string): Promise<Entry>;

  /**
   * List directory contents
   * @param path Directory path
   * @param dirName Directory name
   * @returns Promise resolving to array of Entry objects
   */
  static listDir(path: string, dirName: string): Promise<Entry[]>;

  /**
   * Remove directory recursively
   * @param path Directory path
   * @param dirName Directory name
   * @returns Promise resolving to RemoveResult
   */
  static removeRecursively(path: string, dirName: string): Promise<RemoveResult>;

  /**
   * Check if file exists
   * @param path File path
   * @param file File name
   * @returns Promise resolving to boolean indicating existence
   */
  static checkFile(path: string, file: string): Promise<boolean>;

  /**
   * Create file
   * @param path File path
   * @param fileName File name to create
   * @param replace Whether to replace existing file
   * @returns Promise resolving to FileEntry
   */
  static createFile(path: string, fileName: string, replace: boolean): Promise<FileEntry>;

  /**
   * Remove file
   * @param path File path
   * @param fileName File name to remove
   * @returns Promise resolving to RemoveResult
   */
  static removeFile(path: string, fileName: string): Promise<RemoveResult>;

  /**
   * Write file with content
   * @param path File path
   * @param fileName File name
   * @param text Content to write (string, Blob, or ArrayBuffer)
   * @param options Write options
   * @returns Promise indicating write completion
   */
  static writeFile(path: string, fileName: string, text: string | Blob | ArrayBuffer, options: IWriteOptions): Promise<any>;

  /**
   * Write to existing file
   * @param path File path
   * @param fileName File name
   * @param text Content to write
   * @returns Promise indicating write completion
   */
  static writeExistingFile(path: string, fileName: string, text: string | Blob | ArrayBuffer): Promise<void>;

  /**
   * Read file as text
   * @param path File path
   * @param file File name
   * @returns Promise resolving to file content as string
   */
  static readAsText(path: string, file: string): Promise<string>;

  /**
   * Read file as data URL (base64)
   * @param path File path
   * @param file File name
   * @returns Promise resolving to data URL string
   */
  static readAsDataURL(path: string, file: string): Promise<string>;

  /**
   * Read file as binary string
   * @param path File path
   * @param file File name
   * @returns Promise resolving to binary string
   */
  static readAsBinaryString(path: string, file: string): Promise<string>;

  /**
   * Read file as array buffer
   * @param path File path
   * @param file File name
   * @returns Promise resolving to ArrayBuffer
   */
  static readAsArrayBuffer(path: string, file: string): Promise<ArrayBuffer>;

  /**
   * Move file to new location
   * @param path Source file path
   * @param fileName Source file name
   * @param newPath Destination file path
   * @param newFileName New file name
   * @returns Promise resolving to Entry
   */
  static moveFile(path: string, fileName: string, newPath: string, newFileName: string): Promise<Entry>;

  /**
   * Copy file to new location
   * @param path Source file path
   * @param fileName Source file name
   * @param newPath Destination file path
   * @param newFileName New file name
   * @returns Promise resolving to Entry
   */
  static copyFile(path: string, fileName: string, newPath: string, newFileName: string): Promise<Entry>;

  /**
   * Resolve local filesystem URL to Entry
   * @param fileUrl File URL to resolve
   * @returns Promise resolving to Entry
   */
  static resolveLocalFilesystemUrl(fileUrl: string): Promise<Entry>;

  /**
   * Resolve directory URL to DirectoryEntry
   * @param directoryUrl Directory URL to resolve
   * @returns Promise resolving to DirectoryEntry
   */
  static resolveDirectoryUrl(directoryUrl: string): Promise<DirectoryEntry>;

  /**
   * Get directory from DirectoryEntry
   * @param directoryEntry Parent directory entry
   * @param directoryName Directory name to get
   * @param flags Operation flags
   * @returns Promise resolving to DirectoryEntry
   */
  static getDirectory(directoryEntry: DirectoryEntry, directoryName: string, flags: Flags): Promise<DirectoryEntry>;

  /**
   * Get file from DirectoryEntry
   * @param directoryEntry Parent directory entry
   * @param fileName File name to get
   * @param flags Operation flags
   * @returns Promise resolving to FileEntry
   */
  static getFile(directoryEntry: DirectoryEntry, fileName: string, flags: Flags): Promise<FileEntry>;
}

Usage Examples:

import { File } from 'ionic-native';

// Create and write to a file
async function saveUserData(userData: any) {
  try {
    const fileName = 'userdata.json';
    const data = JSON.stringify(userData);
    
    await File.writeFile(File.dataDirectory, fileName, data, { replace: true });
    console.log('User data saved successfully');
  } catch (error) {
    console.error('Error saving user data:', error);
  }
}

// Read file content
async function loadUserData() {
  try {
    const fileName = 'userdata.json';
    const exists = await File.checkFile(File.dataDirectory, fileName);
    
    if (exists) {
      const content = await File.readAsText(File.dataDirectory, fileName);
      return JSON.parse(content);
    } else {
      console.log('User data file does not exist');
      return null;
    }
  } catch (error) {
    console.error('Error loading user data:', error);
    return null;
  }
}

// List directory contents
async function listCacheFiles() {
  try {
    const entries = await File.listDir(File.cacheDirectory, '');
    console.log('Cache files:');
    entries.forEach(entry => {
      console.log(`- ${entry.name} (${entry.isFile ? 'file' : 'directory'})`);
    });
  } catch (error) {
    console.error('Error listing cache files:', error);
  }
}

// Create directory structure
async function setupAppDirectories() {
  try {
    await File.createDir(File.dataDirectory, 'images', false);
    await File.createDir(File.dataDirectory, 'documents', false);
    await File.createDir(File.dataDirectory, 'cache', false);
    console.log('App directories created');
  } catch (error) {
    console.error('Error creating directories:', error);
  }
}

File Transfer

Upload and download files with progress monitoring and advanced configuration options.

/**
 * File upload configuration options
 */
interface FileUploadOptions {
  /** Name of form element. Defaults to 'file' */
  fileKey?: string;
  /** File name to use when saving on server. Defaults to 'image.jpg' */
  fileName?: string;
  /** HTTP method to use - PUT or POST. Defaults to POST */
  httpMethod?: string;
  /** Mime type of data to upload. Defaults to 'image/jpeg' */
  mimeType?: string;
  /** Set of optional key/value pairs to pass in the HTTP request */
  params?: { [key: string]: string };
  /** Whether to upload despite invalid SSL certificate */
  trustAllHosts?: boolean;
  /** Chunked transfer encoding. Defaults to true */
  chunkedMode?: boolean;
  /** Headers to add to the request */
  headers?: { [key: string]: string };
  /** Unique id for the request */
  id?: string;
}

/**
 * File upload result
 */
interface FileUploadResult {
  /** Number of bytes sent to server as part of upload */
  bytesSent: number;
  /** HTTP response code returned by server */
  responseCode: number;
  /** HTTP response returned by server */
  response: string;
  /** HTTP response headers returned by server */
  headers: { [key: string]: string };
}

/**
 * File transfer error
 */
interface FileTransferError {
  /** Error code */
  code: number;
  /** Error source URI */
  source: string;
  /** Error target URI */
  target: string;
  /** HTTP status code (when available) */
  http_status?: number;
  /** Response body (when available) */
  body?: string;
  /** Exception message (when available) */
  exception?: string;
}

/**
 * Transfer class for uploading and downloading files
 */
class Transfer {
  /**
   * Create new Transfer instance
   * @returns Transfer instance
   */
  constructor();

  /**
   * Upload file to remote server
   * @param fileUrl Local file URL to upload
   * @param url Server URL to upload to
   * @param options Upload configuration options
   * @param trustAllHosts Whether to trust all SSL certificates
   * @returns Promise resolving to FileUploadResult
   */
  upload(fileUrl: string, url: string, options?: FileUploadOptions, trustAllHosts?: boolean): Promise<FileUploadResult>;

  /**
   * Download file from remote server
   * @param source Remote file URL to download
   * @param target Local file path to save to
   * @param trustAllHosts Whether to trust all SSL certificates
   * @param options Download options
   * @returns Promise resolving to FileEntry
   */
  download(source: string, target: string, trustAllHosts?: boolean, options?: { [key: string]: any }): Promise<any>;

  /**
   * Set progress listener for transfer operations
   * @param listener Progress callback function
   */
  onProgress(listener: (event: ProgressEvent) => any): void;

  /**
   * Abort the file transfer
   */
  abort(): void;
}

Usage Examples:

import { Transfer, FileUploadOptions } from 'ionic-native';

// Upload file with progress monitoring
async function uploadPhoto(localFileUri: string) {
  const transfer = new Transfer();
  
  // Set up progress monitoring
  transfer.onProgress((progress) => {
    const percentage = (progress.loaded / progress.total) * 100;
    console.log(`Upload progress: ${percentage.toFixed(2)}%`);
  });

  const options: FileUploadOptions = {
    fileKey: 'photo',
    fileName: 'photo.jpg',
    mimeType: 'image/jpeg',
    params: {
      userId: '12345',
      albumId: 'vacation2023'
    },
    headers: {
      'Authorization': 'Bearer your-token-here'
    }
  };

  try {
    const result = await transfer.upload(localFileUri, 'https://api.example.com/upload', options);
    console.log('Upload successful:', result);
    console.log('Server response:', result.response);
  } catch (error) {
    console.error('Upload failed:', error);
  }
}

// Download file with error handling
async function downloadDocument(remoteUrl: string, localPath: string) {
  const transfer = new Transfer();
  
  try {
    const fileEntry = await transfer.download(remoteUrl, localPath, false, {
      headers: {
        'Authorization': 'Bearer your-token-here'
      }
    });
    
    console.log('Download successful:', fileEntry.toURL());
    return fileEntry;
  } catch (error) {
    console.error('Download failed:', error);
    throw error;
  }
}

SQLite Database

Local SQLite database operations for structured data storage and querying.

/**
 * SQLite database configuration
 */
interface SQLiteConfig {
  /** Database name */
  name: string;
  /** Database location (default, Documents, Library) */
  location?: string;
  /** iOS database location (Library, Documents, Shared) */
  iosDatabaseLocation?: string;
  /** Android database location */
  androidDatabaseLocation?: string;
  /** Android lock workaround */
  androidLockWorkaround?: number;
  /** Create from location */
  createFromLocation?: number;
}

/**
 * SQL result set for query results
 */
interface SQLiteResultSet {
  /** Number of rows returned by query */
  rows: SQLiteResultSetRowList;
  /** Number of rows affected by INSERT, UPDATE, or DELETE */
  rowsAffected: number;
  /** Row ID of last inserted row (INSERT only) */
  insertId: string;
}

/**
 * SQL result row list
 */
interface SQLiteResultSetRowList {
  /** Number of rows */
  length: number;
  /** Get item at specific index */
  item(index: number): any;
}

/**
 * SQL transaction interface
 */
interface SQLiteTransaction {
  /**
   * Execute SQL statement
   * @param sql SQL statement to execute
   * @param values Parameter values for SQL statement
   * @param success Success callback with results
   * @param error Error callback
   */
  executeSql(
    sql: string,
    values?: any[],
    success?: (tx: SQLiteTransaction, result: SQLiteResultSet) => void,
    error?: (tx: SQLiteTransaction, error: any) => boolean
  ): void;
}

/**
 * SQLite database object
 */
interface SQLiteObject {
  /**
   * Open database connection
   * @returns Promise indicating database is ready
   */
  open(): Promise<any>;

  /**
   * Close database connection
   * @returns Promise indicating database is closed
   */
  close(): Promise<any>;

  /**
   * Execute SQL statement
   * @param statement SQL statement
   * @param params Statement parameters
   * @returns Promise resolving to result set
   */
  executeSql(statement: string, params?: any[]): Promise<any>;

  /**
   * Add SQL statement to transaction queue
   * @param statement SQL statement
   * @param values Statement values
   * @returns Promise resolving to result set
   */
  addTransaction(statement: string, values?: any[]): Promise<any>;

  /**
   * Execute transaction
   * @param fn Transaction function
   * @returns Promise indicating transaction completion
   */
  transaction(fn: (tx: SQLiteTransaction) => void): Promise<any>;

  /**
   * Execute read-only transaction
   * @param fn Transaction function
   * @returns Promise indicating transaction completion
   */
  readTransaction(fn: (tx: SQLiteTransaction) => void): Promise<any>;

  /**
   * Start next transaction from queue
   * @returns Promise indicating transaction completion
   */
  startNextTransaction(): Promise<any>;

  /**
   * Delete database
   * @returns Promise indicating deletion completion
   */
  deleteDatabase(): Promise<any>;
}

/**
 * SQLite class for database operations
 */
class SQLite {
  /**
   * Create SQLite database instance
   * @param config Database configuration
   * @returns SQLiteObject instance
   */
  static create(config: SQLiteConfig): SQLiteObject;
}

Usage Examples:

import { SQLite, SQLiteObject } from 'ionic-native';

// Create and initialize database
async function initDatabase(): Promise<SQLiteObject> {
  const db = SQLite.create({
    name: 'app.db',
    location: 'default'
  });

  try {
    await db.open();
    
    // Create tables
    await db.executeSql(`
      CREATE TABLE IF NOT EXISTS users (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        name TEXT NOT NULL,
        email TEXT UNIQUE NOT NULL,
        created_at DATETIME DEFAULT CURRENT_TIMESTAMP
      )
    `, []);

    await db.executeSql(`
      CREATE TABLE IF NOT EXISTS settings (
        key TEXT PRIMARY KEY,
        value TEXT NOT NULL
      )
    `, []);

    console.log('Database initialized successfully');
    return db;
  } catch (error) {
    console.error('Error initializing database:', error);
    throw error;
  }
}

// Insert user data
async function createUser(db: SQLiteObject, name: string, email: string) {
  try {
    const result = await db.executeSql(`
      INSERT INTO users (name, email) VALUES (?, ?)
    `, [name, email]);
    
    console.log('User created with ID:', result.insertId);
    return result.insertId;
  } catch (error) {
    console.error('Error creating user:', error);
    throw error;
  }
}

// Query users
async function getUsers(db: SQLiteObject) {
  try {
    const result = await db.executeSql('SELECT * FROM users ORDER BY created_at DESC', []);
    
    const users = [];
    for (let i = 0; i < result.rows.length; i++) {
      users.push(result.rows.item(i));
    }
    
    return users;
  } catch (error) {
    console.error('Error getting users:', error);
    throw error;
  }
}

// Use transactions for multiple operations
async function transferData(db: SQLiteObject, fromUserId: number, toUserId: number, amount: number) {
  try {
    await db.transaction((tx) => {
      tx.executeSql(`
        UPDATE accounts SET balance = balance - ? WHERE user_id = ?
      `, [amount, fromUserId]);
      
      tx.executeSql(`
        UPDATE accounts SET balance = balance + ? WHERE user_id = ?
      `, [amount, toUserId]);
      
      tx.executeSql(`
        INSERT INTO transactions (from_user_id, to_user_id, amount, created_at) 
        VALUES (?, ?, ?, datetime('now'))
      `, [fromUserId, toUserId, amount]);
    });
    
    console.log('Transfer completed successfully');
  } catch (error) {
    console.error('Transfer failed:', error);
    throw error;
  }
}

Secure Storage

Encrypted key-value storage for sensitive data like tokens, passwords, and user credentials.

/**
 * SecureStorage instance for encrypted key-value storage
 */
interface SecureStorageObject {
  /**
   * Get value for key from secure storage
   * @param key Storage key
   * @returns Promise resolving to stored value
   */
  get(key: string): Promise<string>;

  /**
   * Set key-value pair in secure storage
   * @param key Storage key
   * @param value Value to store
   * @returns Promise indicating storage completion
   */
  set(key: string, value: string): Promise<any>;

  /**
   * Remove key from secure storage
   * @param key Storage key to remove
   * @returns Promise resolving to removed key
   */
  remove(key: string): Promise<string>;

  /**
   * Get all keys from secure storage
   * @returns Promise resolving to array of keys
   */
  keys(): Promise<string[]>;

  /**
   * Clear all data from secure storage
   * @returns Promise indicating clear completion
   */
  clear(): Promise<any>;
}

/**
 * SecureStorage class for creating encrypted storage instances
 */
class SecureStorage {
  /**
   * Create SecureStorage instance
   * @returns SecureStorageObject instance
   */
  constructor();

  /**
   * Create secure storage with identifier
   * @param store Storage identifier
   * @returns Promise resolving to SecureStorageObject
   */
  create(store: string): Promise<SecureStorageObject>;
}

Usage Examples:

import { SecureStorage } from 'ionic-native';

// Create secure storage instance
let secureStorage: any;

async function initSecureStorage() {
  try {
    const storage = new SecureStorage();
    secureStorage = await storage.create('app_secure_store');
    console.log('Secure storage initialized');
  } catch (error) {
    console.error('Error initializing secure storage:', error);
  }
}

// Store sensitive data
async function storeCredentials(username: string, token: string) {
  try {
    await secureStorage.set('username', username);
    await secureStorage.set('auth_token', token);
    console.log('Credentials stored securely');
  } catch (error) {
    console.error('Error storing credentials:', error);
  }
}

// Retrieve sensitive data
async function getCredentials() {
  try {
    const username = await secureStorage.get('username');
    const token = await secureStorage.get('auth_token');
    
    return { username, token };
  } catch (error) {
    console.error('Error retrieving credentials:', error);
    return null;
  }
}

// List all stored keys
async function listStoredKeys() {
  try {
    const keys = await secureStorage.keys();
    console.log('Stored keys:', keys);
    return keys;
  } catch (error) {
    console.error('Error listing keys:', error);
    return [];
  }
}

// Clear all secure storage
async function clearAllSecureData() {
  try {
    await secureStorage.clear();
    console.log('All secure data cleared');
  } catch (error) {
    console.error('Error clearing secure data:', error);
  }
}

Native Storage

Simple key-value storage using native storage mechanisms for non-sensitive data.

/**
 * NativeStorage class for simple key-value storage
 */
class NativeStorage {
  /**
   * Store item with key
   * @param reference Storage key
   * @param value Value to store (will be JSON serialized)
   * @returns Promise indicating storage completion
   */
  static setItem(reference: string, value: any): Promise<any>;

  /**
   * Get item by key
   * @param reference Storage key
   * @returns Promise resolving to stored value (JSON parsed)
   */
  static getItem(reference: string): Promise<any>;

  /**
   * Remove item by key
   * @param reference Storage key to remove
   * @returns Promise indicating removal completion
   */
  static remove(reference: string): Promise<any>;

  /**
   * Clear all stored data
   * @returns Promise indicating clear completion
   */
  static clear(): Promise<any>;

  /**
   * Get all storage keys
   * @returns Promise resolving to array of keys
   */
  static keys(): Promise<string[]>;
}

Usage Examples:

import { NativeStorage } from 'ionic-native';

// Store user preferences
async function saveUserPreferences(preferences: any) {
  try {
    await NativeStorage.setItem('user_preferences', preferences);
    console.log('User preferences saved');
  } catch (error) {
    console.error('Error saving preferences:', error);
  }
}

// Load user preferences
async function loadUserPreferences() {
  try {
    const preferences = await NativeStorage.getItem('user_preferences');
    return preferences;
  } catch (error) {
    console.log('No preferences found, using defaults');
    return getDefaultPreferences();
  }
}

// Store app settings
async function saveAppSettings(settings: any) {
  try {
    await NativeStorage.setItem('app_settings', settings);
    await NativeStorage.setItem('last_updated', new Date().toISOString());
    console.log('App settings saved');
  } catch (error) {
    console.error('Error saving app settings:', error);
  }
}

// Cache API responses
async function cacheApiResponse(key: string, data: any, ttl: number = 3600000) {
  try {
    const cacheItem = {
      data,
      timestamp: Date.now(),
      ttl
    };
    
    await NativeStorage.setItem(`cache_${key}`, cacheItem);
    console.log(`Cached data for key: ${key}`);
  } catch (error) {
    console.error('Error caching data:', error);
  }
}

// Get cached data with expiration check
async function getCachedData(key: string) {
  try {
    const cacheItem = await NativeStorage.getItem(`cache_${key}`);
    const now = Date.now();
    
    if (now - cacheItem.timestamp < cacheItem.ttl) {
      return cacheItem.data;
    } else {
      await NativeStorage.remove(`cache_${key}`);
      return null;
    }
  } catch (error) {
    return null;
  }
}

// List all storage keys
async function listAllStorageKeys() {
  try {
    const keys = await NativeStorage.keys();
    console.log('Storage keys:', keys);
    return keys;
  } catch (error) {
    console.error('Error listing keys:', error);
    return [];
  }
}

Zip Archive Utilities

Extract files from ZIP archives with progress tracking for handling compressed file downloads and updates.

/**
 * Zip utilities class for archive extraction
 */
class Zip {
  /**
   * Extract files from a ZIP archive to a destination folder
   * @param sourceZip Path to the source ZIP file
   * @param destUrl Destination folder path for extraction
   * @param onProgress Optional callback for progress updates
   * @returns Promise that resolves with 0 for success, -1 for error
   */
  static unzip(
    sourceZip: string, 
    destUrl: string, 
    onProgress?: (progress: { loaded: number; total: number }) => void
  ): Promise<number>;
}

Usage Examples:

import { Zip } from 'ionic-native';

// Basic ZIP extraction
try {
  const result = await Zip.unzip('/path/to/archive.zip', '/path/to/destination/');
  if (result === 0) {
    console.log('ZIP extraction successful');
  } else {
    console.log('ZIP extraction failed');
  }
} catch (error) {
  console.error('Extraction error:', error);
}

// ZIP extraction with progress tracking
Zip.unzip(
  '/path/to/large-archive.zip', 
  '/path/to/destination/',
  (progress) => {
    const percent = Math.round((progress.loaded / progress.total) * 100);
    console.log(`Extraction progress: ${percent}%`);
    // Update UI progress bar
    updateProgressBar(percent);
  }
).then((result) => {
  if (result === 0) {
    console.log('Large archive extracted successfully');
    showSuccessMessage();
  } else {
    console.log('Large archive extraction failed');
    showErrorMessage();
  }
}).catch((error) => {
  console.error('Extraction failed:', error);
  showErrorMessage();
});

// Extract app update ZIP file
async function extractAppUpdate(updateZipPath: string) {
  const extractPath = '/path/to/app/updates/';
  
  try {
    const result = await Zip.unzip(
      updateZipPath,
      extractPath,
      (progress) => {
        const percent = (progress.loaded / progress.total) * 100;
        console.log(`Update extraction: ${percent.toFixed(1)}%`);
      }
    );
    
    if (result === 0) {
      console.log('App update extracted successfully');
      return true;
    } else {
      console.error('App update extraction failed');
      return false;
    }
  } catch (error) {
    console.error('Update extraction error:', error);
    return false;
  }
}

docs

analytics-monetization.md

camera-media.md

device-sensors.md

device-system.md

index.md

input-hardware.md

location-maps.md

network-communication.md

notifications-ui.md

security-auth.md

social-sharing.md

storage-files.md

tile.json