Skip to content
이 내용이 도움이 되었나요?

앨범 미디어 선택하기


1. 앨범 미디어 선택하기 (fetchAlbumItems)

지원환경: React NativeReact Native SDKv2.6.0WebViewWebView SDKv2.6.0
실행환경: Toss AppSandbox App

사용자 앨범에서 사진·동영상을 선택해 가져오는 함수예요.
사진과 동영상을 동시에 선택할 수 있으며, 사용자가 선택을 취소하면 빈 배열 []을 반환해요.

시그니처

typescript
function fetchAlbumItems(options?: FetchAlbumItemsOptions): Promise<AlbumItemResponse[]>;

파라미터

  • optionsFetchAlbumItemsOptions

    조회 옵션을 담은 객체예요. 자세한 타입은 아래 FetchAlbumItemsOptions를 참고하세요.

반환값

  • Promise<AlbumItemResponse[]>

    선택한 미디어 목록을 반환해요. 사용자가 취소하면 빈 배열을 반환해요.

에러

에러 코드발생 조건
NOT_ALLOWED앨범 접근이 허용되지 않았을 때
INVALID_REQUEST요청 파라미터가 올바르지 않을 때
INVALID_DATA미디어 데이터가 유효하지 않을 때
UNSUPPORTED_APP_VERSION토스앱 버전이 5.261.0보다 낮을 때

예제

tsx
import { fetchAlbumItems } from '@apps-in-toss/web-framework';

async function pickMedia() {
  try {
    const items = await fetchAlbumItems({
      types: ['PHOTO', 'VIDEO'],
      maxCount: 5,
      base64: true,
    });

    if (items.length === 0) {
      console.log('선택이 취소되었어요.');
      return;
    }

    items.forEach((item) => {
      console.log(item.type, item.id);
    });
  } catch (error) {
    console.error('앨범 조회 오류:', error.code);
  }
}
tsx
import { fetchAlbumItems } from '@apps-in-toss/framework';

async function pickMedia() {
  try {
    const items = await fetchAlbumItems({
      types: ['PHOTO', 'VIDEO'],
      maxCount: 5,
      base64: true,
    });

    if (items.length === 0) {
      console.log('선택이 취소되었어요.');
      return;
    }

    items.forEach((item) => {
      console.log(item.type, item.id);
    });
  } catch (error) {
    console.error('앨범 조회 오류:', error.code);
  }
}

FetchAlbumItemsOptions

typescript
interface FetchAlbumItemsOptions {
  types?: AlbumItemType[];
  maxCount?: number;
  maxWidth?: number;
  base64?: boolean;
}

프로퍼티:

  • typesArray<'PHOTO' | 'VIDEO'>

    가져올 미디어 유형 목록이에요. 'PHOTO'(사진), 'VIDEO'(동영상) 중 선택할 수 있어요. 지정하지 않으면 사진만 가져와요.

  • maxCountnumber · 10

    가져올 항목의 최대 개수예요.

  • maxWidthnumber · 1024

    이미지의 최대 폭이에요. 단위는 픽셀이에요.

  • base64boolean · false

    이미지의 dataUri를 Base64 문자열로 반환할지 여부예요.

AlbumItemResponse

typescript
interface AlbumItemResponse {
  id: string;
  dataUri: string;
  type: AlbumItemType;
}

프로퍼티:

  • idstring

    항목의 고유 ID예요.

  • dataUristring

    미디어 데이터 URI예요. typePHOTO이면서 base64 옵션이 true이면 Base64 문자열로 반환돼요.

  • type'PHOTO' | 'VIDEO'

    미디어 유형이에요.


2. 앨범 가져오기 (fetchAlbumPhotos)

지원환경: React NativeReact Native SDKv1.0.3WebViewWebView SDKv1.0.3
실행환경: Toss AppSandbox App

새 버전이 있어요

fetchAlbumPhotos는 사진만 지원해요.
사진과 동영상을 함께 선택하거나 더 세밀한 제어가 필요하다면 fetchAlbumItems를 사용해 주세요.

사용자 앨범에서 사진 목록을 불러오는 함수예요.
최대 개수와 해상도를 설정할 수 있어요.

시그니처

typescript
function fetchAlbumPhotos(options: { maxCount: number; maxWidth: number; base64: boolean }): Promise<ImageResponse[]>;

파라미터

  • options필수

    조회 옵션을 담은 객체예요.

    • options.maxCountnumber · 10

      가져올 사진의 최대 개수예요.

    • options.maxWidthnumber · 1024

      사진의 최대 폭이에요. 단위는 픽셀이에요.

    • options.base64boolean · false

      이미지를 Base64 형식으로 반환할지 설정해요.

반환값

  • Promise<ImageResponse[]>

    앨범 사진의 고유 ID와 데이터 URI를 포함한 배열을 반환해요.

예제

js
import { fetchAlbumPhotos, FetchAlbumPhotosPermissionError } from '@apps-in-toss/web-framework';

async function handleFetchAlbumPhotos() {
  try {
    const response = await fetchAlbumPhotos({ base64: true, maxWidth: 360 });
    response.forEach((image) => {
      const imageUri = 'data:image/jpeg;base64,' + image.dataUri;
      console.log('이미지 URI:', imageUri);
    });
  } catch (error) {
    if (error instanceof FetchAlbumPhotosPermissionError) {
      console.log('앨범 읽기 권한 없음');
    }
  }
}
tsx
import { fetchAlbumPhotos, FetchAlbumPhotosPermissionError, ImageResponse } from '@apps-in-toss/web-framework';
import { useState } from 'react';

function AlbumPhotoList() {
  const [albumPhotos, setAlbumPhotos] = useState<ImageResponse[]>([]);

  const handlePress = async () => {
    try {
      const response = await fetchAlbumPhotos({ base64: true, maxWidth: 360 });
      setAlbumPhotos((prev) => [...prev, ...response]);
    } catch (error) {
      if (error instanceof FetchAlbumPhotosPermissionError) {
        // 앨범 읽기 권한 없음
      }
    }
  };

  return (
    <div>
      {albumPhotos.map((image) => {
        const imageUri = 'data:image/jpeg;base64,' + image.dataUri;
        return <img src={imageUri} key={image.id} />;
      })}
      <button onClick={handlePress}>앨범 가져오기</button>
    </div>
  );
}
tsx
import { fetchAlbumPhotos, FetchAlbumPhotosPermissionError, ImageResponse } from '@apps-in-toss/framework';
import { useState } from 'react';
import { Alert, Button, Image, View } from 'react-native';

function AlbumPhotoList() {
  const [albumPhotos, setAlbumPhotos] = useState<ImageResponse[]>([]);

  const handlePress = async () => {
    try {
      const response = await fetchAlbumPhotos({ base64: true, maxWidth: 360 });
      setAlbumPhotos((prev) => [...prev, ...response]);
    } catch (error) {
      if (error instanceof FetchAlbumPhotosPermissionError) {
        // 앨범 읽기 권한 없음
      }
    }
  };

  return (
    <View>
      {albumPhotos.map((image) => {
        const imageUri = 'data:image/jpeg;base64,' + image.dataUri;
        return <Image source={{ uri: imageUri }} key={image.id} />;
      })}
      <Button title="앨범 가져오기" onPress={handlePress} />
      <Button
        title="권한 확인하기"
        onPress={async () => {
          const permission = await fetchAlbumPhotos.getPermission();
          Alert.alert(permission);
        }}
      />
      <Button
        title="권한 요청하기"
        onPress={async () => {
          const permission = await fetchAlbumPhotos.openPermissionDialog();
          Alert.alert(permission);
        }}
      />
    </View>
  );
}

예제 앱 체험하기

apps-in-toss-examples 저장소에서 with-album-photos 코드를 내려받거나, 아래 QR 코드를 스캔해 직접 체험해 보세요.