or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

analytics-monetization.mdcamera-media.mddevice-sensors.mddevice-system.mdindex.mdinput-hardware.mdlocation-maps.mdnetwork-communication.mdnotifications-ui.mdsecurity-auth.mdsocial-sharing.mdstorage-files.md
tile.json

storage-files.mddocs/

0

# Storage & File Management

1

2

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

3

4

## Capabilities

5

6

### File System Operations

7

8

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

9

10

```typescript { .api }

11

/**

12

* File system entry base interface

13

*/

14

interface Entry {

15

/** Whether this entry is a file */

16

isFile: boolean;

17

/** Whether this entry is a directory */

18

isDirectory: boolean;

19

/** Name of this entry, excluding the path leading to it */

20

name: string;

21

/** Full absolute path from the root to this entry */

22

fullPath: string;

23

}

24

25

/**

26

* File entry interface extending base Entry

27

*/

28

interface FileEntry extends Entry {

29

/**

30

* Get File object for reading file properties

31

* @param successCallback Success callback with File object

32

* @param errorCallback Error callback with FileError

33

*/

34

file(successCallback: (file: File) => void, errorCallback?: (error: FileError) => void): void;

35

36

/**

37

* Create FileWriter for writing to the file

38

* @param successCallback Success callback with FileWriter

39

* @param errorCallback Error callback with FileError

40

*/

41

createWriter(successCallback: (writer: FileWriter) => void, errorCallback?: (error: FileError) => void): void;

42

}

43

44

/**

45

* Directory entry interface extending base Entry

46

*/

47

interface DirectoryEntry extends Entry {

48

/**

49

* Create directory reader for listing contents

50

* @returns DirectoryReader instance

51

*/

52

createReader(): DirectoryReader;

53

54

/**

55

* Get or create a file within this directory

56

* @param path Relative path to the file

57

* @param options Flags for file operations

58

* @param successCallback Success callback with FileEntry

59

* @param errorCallback Error callback with FileError

60

*/

61

getFile(path: string, options?: Flags, successCallback?: (entry: FileEntry) => void, errorCallback?: (error: FileError) => void): void;

62

63

/**

64

* Get or create a directory within this directory

65

* @param path Relative path to the directory

66

* @param options Flags for directory operations

67

* @param successCallback Success callback with DirectoryEntry

68

* @param errorCallback Error callback with FileError

69

*/

70

getDirectory(path: string, options?: Flags, successCallback?: (entry: DirectoryEntry) => void, errorCallback?: (error: FileError) => void): void;

71

}

72

73

/**

74

* File operation flags

75

*/

76

interface Flags {

77

/** Create file/directory if it doesn't exist */

78

create?: boolean;

79

/** Fail if file/directory already exists (only with create: true) */

80

exclusive?: boolean;

81

}

82

83

/**

84

* File writing options

85

*/

86

interface IWriteOptions {

87

/** Replace existing file content (default: true) */

88

replace?: boolean;

89

/** Append to existing file content */

90

append?: boolean;

91

/** Truncate file before writing */

92

truncate?: number;

93

}

94

95

/**

96

* File removal result

97

*/

98

interface RemoveResult {

99

/** Whether removal was successful */

100

success: boolean;

101

/** Entry that was removed */

102

fileRemoved: Entry;

103

}

104

105

/**

106

* File class providing comprehensive file system operations

107

*/

108

class File {

109

/** Read-only directory where the application is installed */

110

static applicationDirectory: string;

111

112

/** Directory where to store app-specific data files */

113

static dataDirectory: string;

114

115

/** Directory where to store cached data files */

116

static cacheDirectory: string;

117

118

/** Directory where to store external app-specific data files */

119

static externalApplicationStorageDirectory: string;

120

121

/** Directory where to store external data files */

122

static externalDataDirectory: string;

123

124

/** Directory where to store external cached data files */

125

static externalCacheDirectory: string;

126

127

/** External storage (SD card) root directory */

128

static externalRootDirectory: string;

129

130

/** Temporary file directory */

131

static tempDirectory: string;

132

133

/** Synced data directory (iOS) */

134

static syncedDataDirectory: string;

135

136

/** Documents directory */

137

static documentsDirectory: string;

138

139

/** Shared directory */

140

static sharedDirectory: string;

141

142

/**

143

* Get available free disk space

144

* @returns Promise resolving to free space in bytes

145

*/

146

static getFreeDiskSpace(): Promise<number>;

147

148

/**

149

* Check if directory exists

150

* @param path Directory path

151

* @param dir Directory name

152

* @returns Promise resolving to boolean indicating existence

153

*/

154

static checkDir(path: string, dir: string): Promise<boolean>;

155

156

/**

157

* Create directory

158

* @param path Parent directory path

159

* @param dirName Directory name to create

160

* @param replace Whether to replace existing directory

161

* @returns Promise resolving to DirectoryEntry

162

*/

163

static createDir(path: string, dirName: string, replace: boolean): Promise<DirectoryEntry>;

164

165

/**

166

* Remove directory

167

* @param path Directory path

168

* @param dirName Directory name to remove

169

* @returns Promise resolving to RemoveResult

170

*/

171

static removeDir(path: string, dirName: string): Promise<RemoveResult>;

172

173

/**

174

* Move directory to new location

175

* @param path Source directory path

176

* @param dirName Source directory name

177

* @param newPath Destination directory path

178

* @param newDirName New directory name

179

* @returns Promise resolving to DirectoryEntry or Entry

180

*/

181

static moveDir(path: string, dirName: string, newPath: string, newDirName: string): Promise<DirectoryEntry | Entry>;

182

183

/**

184

* Copy directory to new location

185

* @param path Source directory path

186

* @param dirName Source directory name

187

* @param newPath Destination directory path

188

* @param newDirName New directory name

189

* @returns Promise resolving to Entry

190

*/

191

static copyDir(path: string, dirName: string, newPath: string, newDirName: string): Promise<Entry>;

192

193

/**

194

* List directory contents

195

* @param path Directory path

196

* @param dirName Directory name

197

* @returns Promise resolving to array of Entry objects

198

*/

199

static listDir(path: string, dirName: string): Promise<Entry[]>;

200

201

/**

202

* Remove directory recursively

203

* @param path Directory path

204

* @param dirName Directory name

205

* @returns Promise resolving to RemoveResult

206

*/

207

static removeRecursively(path: string, dirName: string): Promise<RemoveResult>;

208

209

/**

210

* Check if file exists

211

* @param path File path

212

* @param file File name

213

* @returns Promise resolving to boolean indicating existence

214

*/

215

static checkFile(path: string, file: string): Promise<boolean>;

216

217

/**

218

* Create file

219

* @param path File path

220

* @param fileName File name to create

221

* @param replace Whether to replace existing file

222

* @returns Promise resolving to FileEntry

223

*/

224

static createFile(path: string, fileName: string, replace: boolean): Promise<FileEntry>;

225

226

/**

227

* Remove file

228

* @param path File path

229

* @param fileName File name to remove

230

* @returns Promise resolving to RemoveResult

231

*/

232

static removeFile(path: string, fileName: string): Promise<RemoveResult>;

233

234

/**

235

* Write file with content

236

* @param path File path

237

* @param fileName File name

238

* @param text Content to write (string, Blob, or ArrayBuffer)

239

* @param options Write options

240

* @returns Promise indicating write completion

241

*/

242

static writeFile(path: string, fileName: string, text: string | Blob | ArrayBuffer, options: IWriteOptions): Promise<any>;

243

244

/**

245

* Write to existing file

246

* @param path File path

247

* @param fileName File name

248

* @param text Content to write

249

* @returns Promise indicating write completion

250

*/

251

static writeExistingFile(path: string, fileName: string, text: string | Blob | ArrayBuffer): Promise<void>;

252

253

/**

254

* Read file as text

255

* @param path File path

256

* @param file File name

257

* @returns Promise resolving to file content as string

258

*/

259

static readAsText(path: string, file: string): Promise<string>;

260

261

/**

262

* Read file as data URL (base64)

263

* @param path File path

264

* @param file File name

265

* @returns Promise resolving to data URL string

266

*/

267

static readAsDataURL(path: string, file: string): Promise<string>;

268

269

/**

270

* Read file as binary string

271

* @param path File path

272

* @param file File name

273

* @returns Promise resolving to binary string

274

*/

275

static readAsBinaryString(path: string, file: string): Promise<string>;

276

277

/**

278

* Read file as array buffer

279

* @param path File path

280

* @param file File name

281

* @returns Promise resolving to ArrayBuffer

282

*/

283

static readAsArrayBuffer(path: string, file: string): Promise<ArrayBuffer>;

284

285

/**

286

* Move file to new location

287

* @param path Source file path

288

* @param fileName Source file name

289

* @param newPath Destination file path

290

* @param newFileName New file name

291

* @returns Promise resolving to Entry

292

*/

293

static moveFile(path: string, fileName: string, newPath: string, newFileName: string): Promise<Entry>;

294

295

/**

296

* Copy file to new location

297

* @param path Source file path

298

* @param fileName Source file name

299

* @param newPath Destination file path

300

* @param newFileName New file name

301

* @returns Promise resolving to Entry

302

*/

303

static copyFile(path: string, fileName: string, newPath: string, newFileName: string): Promise<Entry>;

304

305

/**

306

* Resolve local filesystem URL to Entry

307

* @param fileUrl File URL to resolve

308

* @returns Promise resolving to Entry

309

*/

310

static resolveLocalFilesystemUrl(fileUrl: string): Promise<Entry>;

311

312

/**

313

* Resolve directory URL to DirectoryEntry

314

* @param directoryUrl Directory URL to resolve

315

* @returns Promise resolving to DirectoryEntry

316

*/

317

static resolveDirectoryUrl(directoryUrl: string): Promise<DirectoryEntry>;

318

319

/**

320

* Get directory from DirectoryEntry

321

* @param directoryEntry Parent directory entry

322

* @param directoryName Directory name to get

323

* @param flags Operation flags

324

* @returns Promise resolving to DirectoryEntry

325

*/

326

static getDirectory(directoryEntry: DirectoryEntry, directoryName: string, flags: Flags): Promise<DirectoryEntry>;

327

328

/**

329

* Get file from DirectoryEntry

330

* @param directoryEntry Parent directory entry

331

* @param fileName File name to get

332

* @param flags Operation flags

333

* @returns Promise resolving to FileEntry

334

*/

335

static getFile(directoryEntry: DirectoryEntry, fileName: string, flags: Flags): Promise<FileEntry>;

336

}

337

```

338

339

**Usage Examples:**

340

341

```typescript

342

import { File } from 'ionic-native';

343

344

// Create and write to a file

345

async function saveUserData(userData: any) {

346

try {

347

const fileName = 'userdata.json';

348

const data = JSON.stringify(userData);

349

350

await File.writeFile(File.dataDirectory, fileName, data, { replace: true });

351

console.log('User data saved successfully');

352

} catch (error) {

353

console.error('Error saving user data:', error);

354

}

355

}

356

357

// Read file content

358

async function loadUserData() {

359

try {

360

const fileName = 'userdata.json';

361

const exists = await File.checkFile(File.dataDirectory, fileName);

362

363

if (exists) {

364

const content = await File.readAsText(File.dataDirectory, fileName);

365

return JSON.parse(content);

366

} else {

367

console.log('User data file does not exist');

368

return null;

369

}

370

} catch (error) {

371

console.error('Error loading user data:', error);

372

return null;

373

}

374

}

375

376

// List directory contents

377

async function listCacheFiles() {

378

try {

379

const entries = await File.listDir(File.cacheDirectory, '');

380

console.log('Cache files:');

381

entries.forEach(entry => {

382

console.log(`- ${entry.name} (${entry.isFile ? 'file' : 'directory'})`);

383

});

384

} catch (error) {

385

console.error('Error listing cache files:', error);

386

}

387

}

388

389

// Create directory structure

390

async function setupAppDirectories() {

391

try {

392

await File.createDir(File.dataDirectory, 'images', false);

393

await File.createDir(File.dataDirectory, 'documents', false);

394

await File.createDir(File.dataDirectory, 'cache', false);

395

console.log('App directories created');

396

} catch (error) {

397

console.error('Error creating directories:', error);

398

}

399

}

400

```

401

402

### File Transfer

403

404

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

405

406

```typescript { .api }

407

/**

408

* File upload configuration options

409

*/

410

interface FileUploadOptions {

411

/** Name of form element. Defaults to 'file' */

412

fileKey?: string;

413

/** File name to use when saving on server. Defaults to 'image.jpg' */

414

fileName?: string;

415

/** HTTP method to use - PUT or POST. Defaults to POST */

416

httpMethod?: string;

417

/** Mime type of data to upload. Defaults to 'image/jpeg' */

418

mimeType?: string;

419

/** Set of optional key/value pairs to pass in the HTTP request */

420

params?: { [key: string]: string };

421

/** Whether to upload despite invalid SSL certificate */

422

trustAllHosts?: boolean;

423

/** Chunked transfer encoding. Defaults to true */

424

chunkedMode?: boolean;

425

/** Headers to add to the request */

426

headers?: { [key: string]: string };

427

/** Unique id for the request */

428

id?: string;

429

}

430

431

/**

432

* File upload result

433

*/

434

interface FileUploadResult {

435

/** Number of bytes sent to server as part of upload */

436

bytesSent: number;

437

/** HTTP response code returned by server */

438

responseCode: number;

439

/** HTTP response returned by server */

440

response: string;

441

/** HTTP response headers returned by server */

442

headers: { [key: string]: string };

443

}

444

445

/**

446

* File transfer error

447

*/

448

interface FileTransferError {

449

/** Error code */

450

code: number;

451

/** Error source URI */

452

source: string;

453

/** Error target URI */

454

target: string;

455

/** HTTP status code (when available) */

456

http_status?: number;

457

/** Response body (when available) */

458

body?: string;

459

/** Exception message (when available) */

460

exception?: string;

461

}

462

463

/**

464

* Transfer class for uploading and downloading files

465

*/

466

class Transfer {

467

/**

468

* Create new Transfer instance

469

* @returns Transfer instance

470

*/

471

constructor();

472

473

/**

474

* Upload file to remote server

475

* @param fileUrl Local file URL to upload

476

* @param url Server URL to upload to

477

* @param options Upload configuration options

478

* @param trustAllHosts Whether to trust all SSL certificates

479

* @returns Promise resolving to FileUploadResult

480

*/

481

upload(fileUrl: string, url: string, options?: FileUploadOptions, trustAllHosts?: boolean): Promise<FileUploadResult>;

482

483

/**

484

* Download file from remote server

485

* @param source Remote file URL to download

486

* @param target Local file path to save to

487

* @param trustAllHosts Whether to trust all SSL certificates

488

* @param options Download options

489

* @returns Promise resolving to FileEntry

490

*/

491

download(source: string, target: string, trustAllHosts?: boolean, options?: { [key: string]: any }): Promise<any>;

492

493

/**

494

* Set progress listener for transfer operations

495

* @param listener Progress callback function

496

*/

497

onProgress(listener: (event: ProgressEvent) => any): void;

498

499

/**

500

* Abort the file transfer

501

*/

502

abort(): void;

503

}

504

```

505

506

**Usage Examples:**

507

508

```typescript

509

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

510

511

// Upload file with progress monitoring

512

async function uploadPhoto(localFileUri: string) {

513

const transfer = new Transfer();

514

515

// Set up progress monitoring

516

transfer.onProgress((progress) => {

517

const percentage = (progress.loaded / progress.total) * 100;

518

console.log(`Upload progress: ${percentage.toFixed(2)}%`);

519

});

520

521

const options: FileUploadOptions = {

522

fileKey: 'photo',

523

fileName: 'photo.jpg',

524

mimeType: 'image/jpeg',

525

params: {

526

userId: '12345',

527

albumId: 'vacation2023'

528

},

529

headers: {

530

'Authorization': 'Bearer your-token-here'

531

}

532

};

533

534

try {

535

const result = await transfer.upload(localFileUri, 'https://api.example.com/upload', options);

536

console.log('Upload successful:', result);

537

console.log('Server response:', result.response);

538

} catch (error) {

539

console.error('Upload failed:', error);

540

}

541

}

542

543

// Download file with error handling

544

async function downloadDocument(remoteUrl: string, localPath: string) {

545

const transfer = new Transfer();

546

547

try {

548

const fileEntry = await transfer.download(remoteUrl, localPath, false, {

549

headers: {

550

'Authorization': 'Bearer your-token-here'

551

}

552

});

553

554

console.log('Download successful:', fileEntry.toURL());

555

return fileEntry;

556

} catch (error) {

557

console.error('Download failed:', error);

558

throw error;

559

}

560

}

561

```

562

563

### SQLite Database

564

565

Local SQLite database operations for structured data storage and querying.

566

567

```typescript { .api }

568

/**

569

* SQLite database configuration

570

*/

571

interface SQLiteConfig {

572

/** Database name */

573

name: string;

574

/** Database location (default, Documents, Library) */

575

location?: string;

576

/** iOS database location (Library, Documents, Shared) */

577

iosDatabaseLocation?: string;

578

/** Android database location */

579

androidDatabaseLocation?: string;

580

/** Android lock workaround */

581

androidLockWorkaround?: number;

582

/** Create from location */

583

createFromLocation?: number;

584

}

585

586

/**

587

* SQL result set for query results

588

*/

589

interface SQLiteResultSet {

590

/** Number of rows returned by query */

591

rows: SQLiteResultSetRowList;

592

/** Number of rows affected by INSERT, UPDATE, or DELETE */

593

rowsAffected: number;

594

/** Row ID of last inserted row (INSERT only) */

595

insertId: string;

596

}

597

598

/**

599

* SQL result row list

600

*/

601

interface SQLiteResultSetRowList {

602

/** Number of rows */

603

length: number;

604

/** Get item at specific index */

605

item(index: number): any;

606

}

607

608

/**

609

* SQL transaction interface

610

*/

611

interface SQLiteTransaction {

612

/**

613

* Execute SQL statement

614

* @param sql SQL statement to execute

615

* @param values Parameter values for SQL statement

616

* @param success Success callback with results

617

* @param error Error callback

618

*/

619

executeSql(

620

sql: string,

621

values?: any[],

622

success?: (tx: SQLiteTransaction, result: SQLiteResultSet) => void,

623

error?: (tx: SQLiteTransaction, error: any) => boolean

624

): void;

625

}

626

627

/**

628

* SQLite database object

629

*/

630

interface SQLiteObject {

631

/**

632

* Open database connection

633

* @returns Promise indicating database is ready

634

*/

635

open(): Promise<any>;

636

637

/**

638

* Close database connection

639

* @returns Promise indicating database is closed

640

*/

641

close(): Promise<any>;

642

643

/**

644

* Execute SQL statement

645

* @param statement SQL statement

646

* @param params Statement parameters

647

* @returns Promise resolving to result set

648

*/

649

executeSql(statement: string, params?: any[]): Promise<any>;

650

651

/**

652

* Add SQL statement to transaction queue

653

* @param statement SQL statement

654

* @param values Statement values

655

* @returns Promise resolving to result set

656

*/

657

addTransaction(statement: string, values?: any[]): Promise<any>;

658

659

/**

660

* Execute transaction

661

* @param fn Transaction function

662

* @returns Promise indicating transaction completion

663

*/

664

transaction(fn: (tx: SQLiteTransaction) => void): Promise<any>;

665

666

/**

667

* Execute read-only transaction

668

* @param fn Transaction function

669

* @returns Promise indicating transaction completion

670

*/

671

readTransaction(fn: (tx: SQLiteTransaction) => void): Promise<any>;

672

673

/**

674

* Start next transaction from queue

675

* @returns Promise indicating transaction completion

676

*/

677

startNextTransaction(): Promise<any>;

678

679

/**

680

* Delete database

681

* @returns Promise indicating deletion completion

682

*/

683

deleteDatabase(): Promise<any>;

684

}

685

686

/**

687

* SQLite class for database operations

688

*/

689

class SQLite {

690

/**

691

* Create SQLite database instance

692

* @param config Database configuration

693

* @returns SQLiteObject instance

694

*/

695

static create(config: SQLiteConfig): SQLiteObject;

696

}

697

```

698

699

**Usage Examples:**

700

701

```typescript

702

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

703

704

// Create and initialize database

705

async function initDatabase(): Promise<SQLiteObject> {

706

const db = SQLite.create({

707

name: 'app.db',

708

location: 'default'

709

});

710

711

try {

712

await db.open();

713

714

// Create tables

715

await db.executeSql(`

716

CREATE TABLE IF NOT EXISTS users (

717

id INTEGER PRIMARY KEY AUTOINCREMENT,

718

name TEXT NOT NULL,

719

email TEXT UNIQUE NOT NULL,

720

created_at DATETIME DEFAULT CURRENT_TIMESTAMP

721

)

722

`, []);

723

724

await db.executeSql(`

725

CREATE TABLE IF NOT EXISTS settings (

726

key TEXT PRIMARY KEY,

727

value TEXT NOT NULL

728

)

729

`, []);

730

731

console.log('Database initialized successfully');

732

return db;

733

} catch (error) {

734

console.error('Error initializing database:', error);

735

throw error;

736

}

737

}

738

739

// Insert user data

740

async function createUser(db: SQLiteObject, name: string, email: string) {

741

try {

742

const result = await db.executeSql(`

743

INSERT INTO users (name, email) VALUES (?, ?)

744

`, [name, email]);

745

746

console.log('User created with ID:', result.insertId);

747

return result.insertId;

748

} catch (error) {

749

console.error('Error creating user:', error);

750

throw error;

751

}

752

}

753

754

// Query users

755

async function getUsers(db: SQLiteObject) {

756

try {

757

const result = await db.executeSql('SELECT * FROM users ORDER BY created_at DESC', []);

758

759

const users = [];

760

for (let i = 0; i < result.rows.length; i++) {

761

users.push(result.rows.item(i));

762

}

763

764

return users;

765

} catch (error) {

766

console.error('Error getting users:', error);

767

throw error;

768

}

769

}

770

771

// Use transactions for multiple operations

772

async function transferData(db: SQLiteObject, fromUserId: number, toUserId: number, amount: number) {

773

try {

774

await db.transaction((tx) => {

775

tx.executeSql(`

776

UPDATE accounts SET balance = balance - ? WHERE user_id = ?

777

`, [amount, fromUserId]);

778

779

tx.executeSql(`

780

UPDATE accounts SET balance = balance + ? WHERE user_id = ?

781

`, [amount, toUserId]);

782

783

tx.executeSql(`

784

INSERT INTO transactions (from_user_id, to_user_id, amount, created_at)

785

VALUES (?, ?, ?, datetime('now'))

786

`, [fromUserId, toUserId, amount]);

787

});

788

789

console.log('Transfer completed successfully');

790

} catch (error) {

791

console.error('Transfer failed:', error);

792

throw error;

793

}

794

}

795

```

796

797

### Secure Storage

798

799

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

800

801

```typescript { .api }

802

/**

803

* SecureStorage instance for encrypted key-value storage

804

*/

805

interface SecureStorageObject {

806

/**

807

* Get value for key from secure storage

808

* @param key Storage key

809

* @returns Promise resolving to stored value

810

*/

811

get(key: string): Promise<string>;

812

813

/**

814

* Set key-value pair in secure storage

815

* @param key Storage key

816

* @param value Value to store

817

* @returns Promise indicating storage completion

818

*/

819

set(key: string, value: string): Promise<any>;

820

821

/**

822

* Remove key from secure storage

823

* @param key Storage key to remove

824

* @returns Promise resolving to removed key

825

*/

826

remove(key: string): Promise<string>;

827

828

/**

829

* Get all keys from secure storage

830

* @returns Promise resolving to array of keys

831

*/

832

keys(): Promise<string[]>;

833

834

/**

835

* Clear all data from secure storage

836

* @returns Promise indicating clear completion

837

*/

838

clear(): Promise<any>;

839

}

840

841

/**

842

* SecureStorage class for creating encrypted storage instances

843

*/

844

class SecureStorage {

845

/**

846

* Create SecureStorage instance

847

* @returns SecureStorageObject instance

848

*/

849

constructor();

850

851

/**

852

* Create secure storage with identifier

853

* @param store Storage identifier

854

* @returns Promise resolving to SecureStorageObject

855

*/

856

create(store: string): Promise<SecureStorageObject>;

857

}

858

```

859

860

**Usage Examples:**

861

862

```typescript

863

import { SecureStorage } from 'ionic-native';

864

865

// Create secure storage instance

866

let secureStorage: any;

867

868

async function initSecureStorage() {

869

try {

870

const storage = new SecureStorage();

871

secureStorage = await storage.create('app_secure_store');

872

console.log('Secure storage initialized');

873

} catch (error) {

874

console.error('Error initializing secure storage:', error);

875

}

876

}

877

878

// Store sensitive data

879

async function storeCredentials(username: string, token: string) {

880

try {

881

await secureStorage.set('username', username);

882

await secureStorage.set('auth_token', token);

883

console.log('Credentials stored securely');

884

} catch (error) {

885

console.error('Error storing credentials:', error);

886

}

887

}

888

889

// Retrieve sensitive data

890

async function getCredentials() {

891

try {

892

const username = await secureStorage.get('username');

893

const token = await secureStorage.get('auth_token');

894

895

return { username, token };

896

} catch (error) {

897

console.error('Error retrieving credentials:', error);

898

return null;

899

}

900

}

901

902

// List all stored keys

903

async function listStoredKeys() {

904

try {

905

const keys = await secureStorage.keys();

906

console.log('Stored keys:', keys);

907

return keys;

908

} catch (error) {

909

console.error('Error listing keys:', error);

910

return [];

911

}

912

}

913

914

// Clear all secure storage

915

async function clearAllSecureData() {

916

try {

917

await secureStorage.clear();

918

console.log('All secure data cleared');

919

} catch (error) {

920

console.error('Error clearing secure data:', error);

921

}

922

}

923

```

924

925

### Native Storage

926

927

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

928

929

```typescript { .api }

930

/**

931

* NativeStorage class for simple key-value storage

932

*/

933

class NativeStorage {

934

/**

935

* Store item with key

936

* @param reference Storage key

937

* @param value Value to store (will be JSON serialized)

938

* @returns Promise indicating storage completion

939

*/

940

static setItem(reference: string, value: any): Promise<any>;

941

942

/**

943

* Get item by key

944

* @param reference Storage key

945

* @returns Promise resolving to stored value (JSON parsed)

946

*/

947

static getItem(reference: string): Promise<any>;

948

949

/**

950

* Remove item by key

951

* @param reference Storage key to remove

952

* @returns Promise indicating removal completion

953

*/

954

static remove(reference: string): Promise<any>;

955

956

/**

957

* Clear all stored data

958

* @returns Promise indicating clear completion

959

*/

960

static clear(): Promise<any>;

961

962

/**

963

* Get all storage keys

964

* @returns Promise resolving to array of keys

965

*/

966

static keys(): Promise<string[]>;

967

}

968

```

969

970

**Usage Examples:**

971

972

```typescript

973

import { NativeStorage } from 'ionic-native';

974

975

// Store user preferences

976

async function saveUserPreferences(preferences: any) {

977

try {

978

await NativeStorage.setItem('user_preferences', preferences);

979

console.log('User preferences saved');

980

} catch (error) {

981

console.error('Error saving preferences:', error);

982

}

983

}

984

985

// Load user preferences

986

async function loadUserPreferences() {

987

try {

988

const preferences = await NativeStorage.getItem('user_preferences');

989

return preferences;

990

} catch (error) {

991

console.log('No preferences found, using defaults');

992

return getDefaultPreferences();

993

}

994

}

995

996

// Store app settings

997

async function saveAppSettings(settings: any) {

998

try {

999

await NativeStorage.setItem('app_settings', settings);

1000

await NativeStorage.setItem('last_updated', new Date().toISOString());

1001

console.log('App settings saved');

1002

} catch (error) {

1003

console.error('Error saving app settings:', error);

1004

}

1005

}

1006

1007

// Cache API responses

1008

async function cacheApiResponse(key: string, data: any, ttl: number = 3600000) {

1009

try {

1010

const cacheItem = {

1011

data,

1012

timestamp: Date.now(),

1013

ttl

1014

};

1015

1016

await NativeStorage.setItem(`cache_${key}`, cacheItem);

1017

console.log(`Cached data for key: ${key}`);

1018

} catch (error) {

1019

console.error('Error caching data:', error);

1020

}

1021

}

1022

1023

// Get cached data with expiration check

1024

async function getCachedData(key: string) {

1025

try {

1026

const cacheItem = await NativeStorage.getItem(`cache_${key}`);

1027

const now = Date.now();

1028

1029

if (now - cacheItem.timestamp < cacheItem.ttl) {

1030

return cacheItem.data;

1031

} else {

1032

await NativeStorage.remove(`cache_${key}`);

1033

return null;

1034

}

1035

} catch (error) {

1036

return null;

1037

}

1038

}

1039

1040

// List all storage keys

1041

async function listAllStorageKeys() {

1042

try {

1043

const keys = await NativeStorage.keys();

1044

console.log('Storage keys:', keys);

1045

return keys;

1046

} catch (error) {

1047

console.error('Error listing keys:', error);

1048

return [];

1049

}

1050

}

1051

```

1052

1053

### Zip Archive Utilities

1054

1055

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

1056

1057

```typescript { .api }

1058

/**

1059

* Zip utilities class for archive extraction

1060

*/

1061

class Zip {

1062

/**

1063

* Extract files from a ZIP archive to a destination folder

1064

* @param sourceZip Path to the source ZIP file

1065

* @param destUrl Destination folder path for extraction

1066

* @param onProgress Optional callback for progress updates

1067

* @returns Promise that resolves with 0 for success, -1 for error

1068

*/

1069

static unzip(

1070

sourceZip: string,

1071

destUrl: string,

1072

onProgress?: (progress: { loaded: number; total: number }) => void

1073

): Promise<number>;

1074

}

1075

```

1076

1077

**Usage Examples:**

1078

1079

```typescript

1080

import { Zip } from 'ionic-native';

1081

1082

// Basic ZIP extraction

1083

try {

1084

const result = await Zip.unzip('/path/to/archive.zip', '/path/to/destination/');

1085

if (result === 0) {

1086

console.log('ZIP extraction successful');

1087

} else {

1088

console.log('ZIP extraction failed');

1089

}

1090

} catch (error) {

1091

console.error('Extraction error:', error);

1092

}

1093

1094

// ZIP extraction with progress tracking

1095

Zip.unzip(

1096

'/path/to/large-archive.zip',

1097

'/path/to/destination/',

1098

(progress) => {

1099

const percent = Math.round((progress.loaded / progress.total) * 100);

1100

console.log(`Extraction progress: ${percent}%`);

1101

// Update UI progress bar

1102

updateProgressBar(percent);

1103

}

1104

).then((result) => {

1105

if (result === 0) {

1106

console.log('Large archive extracted successfully');

1107

showSuccessMessage();

1108

} else {

1109

console.log('Large archive extraction failed');

1110

showErrorMessage();

1111

}

1112

}).catch((error) => {

1113

console.error('Extraction failed:', error);

1114

showErrorMessage();

1115

});

1116

1117

// Extract app update ZIP file

1118

async function extractAppUpdate(updateZipPath: string) {

1119

const extractPath = '/path/to/app/updates/';

1120

1121

try {

1122

const result = await Zip.unzip(

1123

updateZipPath,

1124

extractPath,

1125

(progress) => {

1126

const percent = (progress.loaded / progress.total) * 100;

1127

console.log(`Update extraction: ${percent.toFixed(1)}%`);

1128

}

1129

);

1130

1131

if (result === 0) {

1132

console.log('App update extracted successfully');

1133

return true;

1134

} else {

1135

console.error('App update extraction failed');

1136

return false;

1137

}

1138

} catch (error) {

1139

console.error('Update extraction error:', error);

1140

return false;

1141

}

1142

}

1143

```