Adding Mobile
1 つのコードベースで iOS、Android、Web のすべてで動作すれば、フォトギャラリーアプリの完成です。モバイル対応に必要な処理を少し変更し、ネイティブツールをインストールして、実機でアプリを動かしましょう。
Import Platform API
まずは、いくつか小さなコードの変更を行いましょう。そうすれば、デバイスにアプリをデプロイしたときに、アプリが正常に動作するようになります。
Ionic Platform APIを、photo.service.tsファイルにインポートしましょう。この API を使えば、現在のデバイスに関する情報を取得することができます。この機能は、アプリが動作しているプラットフォーム(ウェブかモバイルか)に基づいて、どのコードを実行するかを決定するのに役立ちます。
ファイルの上部にあるインポートのリストにPlatformを追加し、PhotoServiceクラスには新しいプロパティplatformを追加します。また、constructor を更新して、ユーザーのプラットフォームを設定する必要があります。
import { Injectable, inject, signal } from '@angular/core';
import { Camera, CameraResultType, CameraSource } from '@capacitor/camera';
import type { Photo } from '@capacitor/camera';
import { Filesystem, Directory } from '@capacitor/filesystem';
import { Preferences } from '@capacitor/preferences';
// CHANGE: Add import
import { Platform } from '@ionic/angular';
@Injectable({
providedIn: 'root',
})
export class PhotoService {
public photos = signal<UserPhoto[]>([]);
private PHOTO_STORAGE: string = 'photos';
// CHANGE: Inject the Platform API to track the app's running platform
private platform = inject(Platform);
// ...existing code...
}
Platform-specific Logic
まず、写真を保存する処理をモバイルに対応させます。savePicture() メソッド内で、アプリが動作しているプラットフォームを確認します。「hybrid」(ネイティブランタイムの Capacitor)であれば、Filesystem.readFile() メソッドで写真ファイルを base64 形式に読み込みます。Web で実行している場合はこれまでと同じ処理を使います。
savePicture()のコードを以下のように更新してください。
// CHANGE: Update the `savePicture()` method
private async savePicture(photo: Photo) {
let base64Data: string | Blob;
// CHANGE: Add platform check
// "hybrid" will detect Cordova or Capacitor
if (this.platform.is('hybrid')) {
// Read the file into base64 format
const file = await Filesystem.readFile({
path: photo.path!,
});
base64Data = file.data;
} else {
base64Data = await this.base64FromPath(photo.webPath!);
}
// Write the file to the data directory
const fileName = Date.now() + '.jpeg';
const savedFile = await Filesystem.writeFile({
path: fileName,
data: base64Data,
directory: Directory.Data,
});
// Use webPath to display the new image instead of base64 since it's
// already loaded into memory
return {
filepath: fileName,
webviewPath: photo.webPath,
};
}
モバイル端末で実行する場合は、filepathをwriteFile()メソッドの結果、つまりsavedFile.uriに設定してください。webviewPathを設定する際には、Capacitor.convertFileSrc()メソッドを使用してください(File Protocol の詳細)。このメソッドを使用するには、photo.service.tsファイルに Capacitor をインポートする必要があります。
import { Injectable, inject, signal } from '@angular/core';
import { Camera, CameraResultType, CameraSource } from '@capacitor/camera';
import type { Photo } from '@capacitor/camera';
// CHANGE: Add import
import { Capacitor } from '@capacitor/core';
import { Filesystem, Directory } from '@capacitor/filesystem';
import { Preferences } from '@capacitor/preferences';
import { Platform } from '@ionic/angular';
// ...existing code...
それでは、savePicture()メソッドを以下のように更新してください。
// CHANGE: Update `savePicture()` method
private async savePicture(photo: Photo) {
let base64Data: string | Blob;
// "hybrid" will detect mobile - iOS or Android
if (this.platform.is('hybrid')) {
const file = await Filesystem.readFile({
path: photo.path!,
});
base64Data = file.data;
} else {
base64Data = await this.base64FromPath(photo.webPath!);
}
// Write the file to the data directory
const fileName = Date.now() + '.jpeg';
const savedFile = await Filesystem.writeFile({
path: fileName,
data: base64Data,
directory: Directory.Data,
});
// CHANGE: Add platform check
if (this.platform.is('hybrid')) {
// Display the new image by rewriting the 'file://' path to HTTP
return {
filepath: savedFile.uri,
webviewPath: Capacitor.convertFileSrc(savedFile.uri),
};
} else {
// Use webPath to display the new image instead of base64 since it's
// already loaded into memory
return {
filepath: fileName,
webviewPath: photo.webPath,
};
}
}
次に loadSaved() メソッドに処理を追加します。モバイルでは Filesystem 上の各写真ファイルを直接参照すれば表示されます。Web では Filesystem API が内部で IndexedDB を使用するため、各画像を Filesystem から base64 形式で読み込む必要があります。loadSaved() メソッドを更新します。
// CHANGE: Update `loadSaved()` method
public async loadSaved(): Promise<void> {
const { value: photoList } = await Preferences.get({ key: this.PHOTO_STORAGE });
const photos = (photoList ? JSON.parse(photoList) : []) as UserPhoto[];
// CHANGE: Add platform check
// If running on the web...
if (!this.platform.is('hybrid')) {
for (const photo of photos) {
const readFile = await Filesystem.readFile({
path: photo.filepath,
directory: Directory.Data,
});
// Web platform only: Load the photo as base64 data
photo.webviewPath = `data:image/jpeg;base64,${readFile.data}`;
}
}
// CHANGE: Set the signal so the gallery view updates
this.photos.set(photos);
}
私たちの Photo Gallery は、現在、ウェブや Android、iOS で動作する 1 つのコードベースで構成されています。
ここまでで photo.service.ts は次のようになります。
import { Injectable, inject, signal } from '@angular/core';
import { Camera, CameraResultType, CameraSource } from '@capacitor/camera';
import type { Photo } from '@capacitor/camera';
import { Capacitor } from '@capacitor/core';
import { Filesystem, Directory } from '@capacitor/filesystem';
import { Preferences } from '@capacitor/preferences';
import { Platform } from '@ionic/angular';
@Injectable({
providedIn: 'root',
})
export class PhotoService {
public photos = signal<UserPhoto[]>([]);
private PHOTO_STORAGE: string = 'photos';
private platform = inject(Platform);
public async addNewToGallery(): Promise<void> {
// Take a photo
const capturedPhoto = await Camera.getPhoto({
resultType: CameraResultType.Uri, // file-based data; provides best performance
source: CameraSource.Camera, // automatically take a new photo with the camera
quality: 100, // highest quality (0 to 100)
});
const savedImageFile = await this.savePicture(capturedPhoto);
this.photos.update((photos) => [savedImageFile, ...photos]);
Preferences.set({
key: this.PHOTO_STORAGE,
value: JSON.stringify(this.photos()),
});
}
private async savePicture(photo: Photo) {
let base64Data: string | Blob;
// "hybrid" will detect Cordova or Capacitor
if (this.platform.is('hybrid')) {
// Read the file into base64 format
const file = await Filesystem.readFile({
path: photo.path!,
});
base64Data = file.data;
} else {
base64Data = await this.base64FromPath(photo.webPath!);
}
// Write the file to the data directory
const fileName = Date.now() + '.jpeg';
const savedFile = await Filesystem.writeFile({
path: fileName,
data: base64Data,
directory: Directory.Data,
});
if (this.platform.is('hybrid')) {
// Display the new image by rewriting the 'file://' path to HTTP
return {
filepath: savedFile.uri,
webviewPath: Capacitor.convertFileSrc(savedFile.uri),
};
} else {
// Use webPath to display the new image instead of base64 since it's
// already loaded into memory
return {
filepath: fileName,
webviewPath: photo.webPath,
};
}
}
private async base64FromPath(path: string): Promise<string> {
const response = await fetch(path);
const blob = await response.blob();
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onerror = reject;
reader.onload = () => {
if (typeof reader.result === 'string') {
resolve(reader.result);
} else {
reject('method did not return a string');
}
};
reader.readAsDataURL(blob);
});
}
public async loadSaved(): Promise<void> {
// Retrieve cached photo array data
const { value: photoList } = await Preferences.get({ key: this.PHOTO_STORAGE });
const photos = (photoList ? JSON.parse(photoList) : []) as UserPhoto[];
// If running on the web...
if (!this.platform.is('hybrid')) {
for (const photo of photos) {
const readFile = await Filesystem.readFile({
path: photo.filepath,
directory: Directory.Data,
});
// Web platform only: Load the photo as base64 data
photo.webviewPath = `data:image/jpeg;base64,${readFile.data}`;
}
}
this.photos.set(photos);
}
}
export interface UserPhoto {
filepath: string;
webviewPath?: string;
}
次に、皆さんが待ち望んでいた部分です。つまり、アプリをデバイスに展開する部分です。