跳到主要內容
版本:v8

加入行動裝置

我們的照片庫應用程式在 iOS、Android 和網路上運行之前,不會是完整的 - 全部使用一個程式碼庫。只需要一些小的邏輯變更來支援行動平台、安裝一些原生工具,然後在裝置上執行應用程式。開始吧!

讓我們從進行一些小的程式碼變更開始 - 然後我們的應用程式在部署到裝置時就會「正常工作」。

平台特定邏輯

首先,我們將更新照片儲存功能以支援行動裝置。我們會根據平台(行動裝置或網路)執行稍微不同的程式碼。從 Ionic Vue 匯入 `Platform` API,並從 Capacitor 的 `core` 套件匯入 `Capacitor`。

import { isPlatform } from '@ionic/vue';
import { Capacitor } from '@capacitor/core';

在 `savePicture` 函數中,檢查應用程式正在哪個平台上運行。如果它是「混合」(Capacitor,原生運行時),則使用 `readFile` 方法將照片檔案讀入 base64 格式。此外,使用 Filesystem API 返回照片的完整檔案路徑。設定 `webviewPath` 時,使用特殊的 `Capacitor.convertFileSrc` 方法(此處有詳細資訊)。否則,在網路上運行應用程式時,使用與之前相同的邏輯。

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 {
// Fetch the photo, read as a blob, then convert to base64 format
const response = await fetch(photo.webPath!);
const blob = await response.blob();
base64Data = (await convertBlobToBase64(blob)) as string;
}
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
// Details: https://ionic.dev.org.tw/docs/building/webview#file-protocol
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` 函數中新增一段新的邏輯。在行動裝置上,我們可以將每個照片檔案直接指向檔案系統,並自動顯示它們。然而,在網路上,我們必須將每個影像從檔案系統讀取到 base64 格式。這是因為檔案系統 API 在底層使用 IndexedDB。更新 `loadSaved` 函數

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;
};

我們的照片庫現在由一個程式碼庫組成,該程式碼庫可在網路、Android 和 iOS 上運行。接下來,您一直在等待的部分 - 將應用程式部署到裝置。