はじめに
-
プラグインをインストールする
Terminal window npm i @capgo/capacitor-photo-libraryTerminal window pnpm add @capgo/capacitor-photo-libraryTerminal window yarn add @capgo/capacitor-photo-libraryTerminal window bun add @capgo/capacitor-photo-library -
プラットフォームを同期する
Terminal window npx cap syncTerminal window pnpm cap syncTerminal window yarn cap syncTerminal window bunx cap sync
プラットフォームパーミッション
Section titled “プラットフォームパーミッション”- iOS:
Info.plistをNSPhotoLibraryUsageDescriptionで更新します(メディアを保存する予定がある場合はNSPhotoLibraryAddUsageDescriptionも必要です)。 - Android: Android 13+ の場合、写真/動画パーミッション(
READ_MEDIA_IMAGES、READ_MEDIA_VIDEO)を宣言します。Capacitor 5 はこれを自動的に処理しますが、カスタムマニフェストを再確認してください。
アクセスをリクエストする
Section titled “アクセスをリクエストする”import { PhotoLibrary } from '@capgo/capacitor-photo-library';
const { state } = await PhotoLibrary.requestAuthorization();if (state !== 'authorized' && state !== 'limited') { throw new Error('写真アクセスが拒否されました');}ギャラリーを読み込む
Section titled “ギャラリーを読み込む”import { Capacitor } from '@capacitor/core';
const { assets, hasMore, nextPage } = await PhotoLibrary.getLibrary({ limit: 100, includeAlbums: false, thumbnailWidth: 256, thumbnailHeight: 256,});
const gallery = assets.map((asset) => ({ id: asset.id, fileName: asset.fileName, created: asset.creationDate, thumbnailUrl: asset.thumbnail ? asset.thumbnail.webPath ?? Capacitor.convertFileSrc(asset.thumbnail.path) : undefined, photoUrl: asset.file ? asset.file.webPath ?? Capacitor.convertFileSrc(asset.file.path) : undefined,}));追加のページを取得するには、PhotoLibrary.getLibrary({ cursor: nextPage }) を呼び出します。
ユーザーにメディアを選択させる
Section titled “ユーザーにメディアを選択させる”const selection = await PhotoLibrary.pickMedia({ selectionLimit: 5, includeVideos: true,});
console.log('ユーザーが選択した', selection.assets.length, '項目');キャッシュされたファイルをクリーンアップする
Section titled “キャッシュされたファイルをクリーンアップする”生成されたサムネイルとエクスポートは、photoLibrary の下にあるアプリキャッシュディレクトリに保存されます。ストレージを再利用する必要がある場合は、お好みのファイル API で削除してください。