설정
Andorid
-
IOS
Info.plist
<key>LSSupportsOpeningDocumentsInPlace</key>
<true/>
<key>UIFileSharingEnabled</key>
<true/>
LSSupportsOpeningDocumentsInPlace
애플리케이션이 파일을 원래 위치에서 직접 열 수 있도록 허용합니다.
예를 들어, 사용자가 iCloud Drive 또는 다른 파일 제공 앱에 저장된 파일을 열 때, 파일을 복사하지 않고 직접 그 위치에서 열 수 있게 됩니다. 이 설정은 사용자가 파일을 수정할 때 원본 파일을 바로 수정할 수 있도록 합니다.
UIFileSharingEnabled
사용자가 iTunes(현재는 Finder)에서 해당 애플리케이션의 파일을 보고, 컴퓨터와 파일을 공유할 수 있습니다. 즉, 사용자가 애플리케이션의 Documents 디렉토리에 저장된 파일을 iTunes 파일 공유를 통해 접근하고 복사하거나 삭제할 수 있게 됩니다.
해당 설정을 하지 않을 시 다운로드 된 파일이 "내 파일"앱에 출력 되지 않는다.
라이브러리
react-native-blob-util
react-native-blob-util은 React Native 애플리케이션에서 파일 처리와 네트워크 요청을 쉽게 할 수 있게 도와주는 라이브러리입니다. 이 라이브러리는 파일 업로드, 다운로드, 파일 시스템 접근, 바이너리 데이터 처리와 같은 다양한 기능을 제공합니다.
설치 방법
npm install --save react-native-blob-util
# 또는
yarn add react-native-blob-util
코드
export const fileDownload = async (url: null | string) => {
try {
const { dirs, writeFile } = RNBlobUtil.fs;
const filename = `classup_${dayjs().format("YYYYMMDD_HHmmss")}`;
// 파일을 다운로드
const response = await RNBlobUtil.fetch("GET", url);
// 응답 헤더에서 Content-Type 가져오기
const contentType =
response.info().headers["Content-Type"] ||
response.info().headers["content-type"];
// Content-Type에 따라 파일 확장자 결정
const extension = mimeToExtension[contentType] || "bin"; // 기본값으로 'bin' 사용
const platformPath =
Platform.OS === "android" ? dirs.LegacyDownloadDir : dirs.DocumentDir;
// 파일 경로 설정
const path = `${platformPath}/${filename}.${extension}`;
// 파일을 로컬에 저장
await writeFile(path, response.data, "base64");
} catch (error) {
console.log(error)
}
};