Adding Mobile
1 つのコードベースで iOS、Android、Web のすべてで動作すれば、フォトギャラリーアプリの完成です。モバイル対応に必要な処理を少し変更し、ネイティブツールをインストールして、実機でアプリを動かしましょう。
Import Platform API
まずは、いくつか小さなコードの変更を行いましょう。そうすれば、デバイスにアプリをデプロイしたときに、アプリが正常に動作するようになります。
Ionic Platform APIを、usePhotoGallery.tsファイルにインポートしましょう。この API を使えば、現在のデバイスに関する情報を取得することができます。この機能は、アプリが動作しているプラットフォーム(ウェブかモバイルか)に基づいて、どのコードを実行するかを決定するのに役立ちます。
ファイルの上部にあるインポートのリストにPlatformを追加してください。そうすることで、isPlatformメソッドを使用できます。
import type { Photo } from '@capacitor/camera';
import { Camera, CameraResultType, CameraSource } from '@capacitor/camera';
import { Filesystem, Directory } from '@capacitor/filesystem';
import { Preferences } from '@capacitor/preferences';
// CHANGE: Add import
import { isPlatform } from '@ionic/vue';
import type { Ref } from 'vue';
import { ref, onMounted, watch } from 'vue';
// ...existing code...
Platform-specific Logic
まず、写真を保存する処理をモバイルに対応させます。savePicture() メソッド内で、アプリが動作しているプラットフォームを確認します。「hybrid」(ネイティブランタイムの Capacitor)であれば、Filesystem.readFile() メソッドで写真ファイルを base64 形式に読み込みます。Web で実行している場合はこれまでと同じ処理を使います。
savePicture()のコードを以下のように更新してください。
// CHANGE: Update the `savePicture()` method
const savePicture = async (photo: Photo, fileName: string): Promise<UserPhoto> => {
let base64Data: string | Blob;
// CHANGE: Add platform check
// "hybrid" will detect mobile - iOS or Android
if (isPlatform('hybrid')) {
const file = await Filesystem.readFile({
path: photo.path!,
});
base64Data = file.data;
} else {
base64Data = await base64FromPath(photo.webPath!);
}
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 の詳細)。このメソッドを使用するには、usePhotoGallery.tsファイルに Capacitor をインポートする必要があります。
import type { Photo } from '@capacitor/camera';
import { Camera, CameraResultType, CameraSource } from '@capacitor/camera';
// CHANGE: Add import
import { Capacitor } from '@capacitor/core';
import { Filesystem, Directory } from '@capacitor/filesystem';
import { Preferences } from '@capacitor/preferences';
import { isPlatform } from '@ionic/vue';
import type { Ref } from 'vue';
import { ref, onMounted, watch } from 'vue';
// ...existing code...
それでは、savePicture()メソッドを以下のように更新してください。
// CHANGE: Update `savePicture()` method
const savePicture = async (photo: Photo, fileName: string): Promise<UserPhoto> => {
let base64Data: string | Blob;
// CHANGE: Add platform check
// "hybrid" will detect mobile - iOS or Android
if (isPlatform('hybrid')) {
const file = await Filesystem.readFile({
path: photo.path!,
});
base64Data = file.data;
} else {
base64Data = await base64FromPath(photo.webPath!);
}
const savedFile = await Filesystem.writeFile({
path: fileName,
data: base64Data,
directory: Directory.Data,
});
// CHANGE: Add platform check
if (isPlatform('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
const loadSaved = async () => {
const photoList = await Preferences.get({ key: PHOTO_STORAGE });
const photosInPreferences = photoList.value ? JSON.parse(photoList.value) : [];
// CHANGE: Add platform check
// If running on the web...
if (!isPlatform('hybrid')) {
for (const photo of photosInPreferences) {
const file = await Filesystem.readFile({
path: photo.filepath,
directory: Directory.Data,
});
// Web platform only: Load the photo as base64 data
photo.webviewPath = `data:image/jpeg;base64,${file.data}`;
}
}
photos.value = photosInPreferences;
};
私たちの Photo Gallery は、現在、ウェブや Android、iOS で動作する 1 つのコードベースで構成されています。
ここまでで usePhotoGallery.ts は次のようになります。
import type { Photo } from '@capacitor/camera';
import { Camera, CameraResultType, CameraSource } from '@capacitor/camera';
import { Capacitor } from '@capacitor/core';
import { Filesystem, Directory } from '@capacitor/filesystem';
import { Preferences } from '@capacitor/preferences';
import { isPlatform } from '@ionic/vue';
import type { Ref } from 'vue';
import { ref, onMounted, watch } from 'vue';
export const usePhotoGallery = (): {
addNewToGallery: () => Promise<void>;
photos: Ref<UserPhoto[]>;
} => {
const photos = ref<UserPhoto[]>([]);
const PHOTO_STORAGE = 'photos';
const addNewToGallery = async () => {
// 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 fileName = Date.now() + '.jpeg';
// Save the picture and add it to photo collection
const savedImageFile = await savePicture(capturedPhoto, fileName);
photos.value = [savedImageFile, ...photos.value];
};
const savePicture = async (photo: Photo, fileName: string): Promise<UserPhoto> => {
let base64Data: string | Blob;
// "hybrid" will detect mobile - iOS or Android
if (isPlatform('hybrid')) {
const file = await Filesystem.readFile({
path: photo.path!,
});
base64Data = file.data;
} else {
base64Data = await base64FromPath(photo.webPath!);
}
const savedFile = await Filesystem.writeFile({
path: fileName,
data: base64Data,
directory: Directory.Data,
});
if (isPlatform('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,
};
}
};
const base64FromPath = async (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);
});
};
const cachePhotos = () => {
Preferences.set({
key: PHOTO_STORAGE,
value: JSON.stringify(photos.value),
});
};
const loadSaved = async () => {
const photoList = await Preferences.get({ key: PHOTO_STORAGE });
const photosInPreferences = photoList.value ? JSON.parse(photoList.value) : [];
// If running on the web...
if (!isPlatform('hybrid')) {
for (const photo of photosInPreferences) {
const file = await Filesystem.readFile({
path: photo.filepath,
directory: Directory.Data,
});
// Web platform only: Load the photo as base64 data
photo.webviewPath = `data:image/jpeg;base64,${file.data}`;
}
}
photos.value = photosInPreferences;
};
onMounted(loadSaved);
watch(photos, cachePhotos);
return {
addNewToGallery,
photos,
};
};
export interface UserPhoto {
filepath: string;
webviewPath?: string;
}
次に、皆さんが待ち望んでいた部分です。つまり、アプリをデバイスに展開する部分です。