コンテンツへスキップ

はじめに

  1. プラグインをインストールする

    Terminal window
    npm i @capgo/capacitor-photo-library
  2. プラットフォームを同期する

    Terminal window
    npx cap sync

プラットフォームパーミッション

Section titled “プラットフォームパーミッション”
  • iOS: Info.plistNSPhotoLibraryUsageDescription で更新します(メディアを保存する予定がある場合は NSPhotoLibraryAddUsageDescription も必要です)。
  • Android: Android 13+ の場合、写真/動画パーミッション(READ_MEDIA_IMAGESREAD_MEDIA_VIDEO)を宣言します。Capacitor 5 はこれを自動的に処理しますが、カスタムマニフェストを再確認してください。
import { PhotoLibrary } from '@capgo/capacitor-photo-library';
const { state } = await PhotoLibrary.requestAuthorization();
if (state !== 'authorized' && state !== 'limited') {
throw new Error('写真アクセスが拒否されました');
}
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 で削除してください。