React-Native Video Download

이기훈·2021년 5월 18일
0

Today-I-Coded

목록 보기
1/1

Today I Coded

React-Native로 동영상을 처리하다 보니 동영상을 다운로드를 해야 했다.
검색해보니 React-Native에서 주로 사용하고 있는 모듈은 react-native-fs였다.
react-native-fs Document에서는 react-native-fs를 Native filesystem access for react-native로 설명하고 있다.

react-native 0.60이전 버전에서는 react-native에 모듈을 링크하기 위해서 여러가지 설정들을 해줘야 하지만 0.60이상에서는 android에서는 새롭게 빌드만 해주면 되고, IOS에서는 pod install정도만 다시 해주면 된다.

fs를 사용한 비디오 다운로드는 아래와 같다.

import RNFS from'react-native-fs'

const LOCAL_PATH_TO_VIDEO = Platform.OS === 'ios' ? `${RNFS.DocumentDirectoryPath}/${timestamp}.mp4` : `${RNFS.ExternalDirectoryPath}/${timestamp}.mp4`

RNFS.downloadFile({
  fromUrl: REMOTE_URI_OF_VIDEO,
  toFile: LOCAL_PATH_TO_VIDEO,
}).then((res) => {
  console.log('successful video download!')
}).catch((err) => {
  console.error(err.message, err.code)
})

여기서 toFile에서 path를 제대로 확인을 하지 못 해서 어디로 다운이 되었는지 확인이 어려웠다.
그래서 toFile에서 rn-fetch-blob을 사용해서 경로를 지정하고 다운로드를 하였더니 다운이 완료 되었다.

import RNFS from'react-native-fs'
import RNFetchBlob from 'rn-fetch-blob';


const path = RNFetchBlob.fs.dirs.DownloadDir;

const LOCAL_PATH_TO_VIDEO = Platform.OS === 'ios' ? `${RNFS.DocumentDirectoryPath}/${timestamp}.mp4` : `${path}.mp4`

RNFS.downloadFile({
  fromUrl: REMOTE_URI_OF_VIDEO,
  toFile: LOCAL_PATH_TO_VIDEO,
}).then((res) => {
  console.log('successful video download!')
}).catch((err) => {
  console.error(err.message, err.code)
})

다운로드 할 때 옵션을 지정해 줄 수 있으며 다운로드 option은 아래와 같다

type DownloadFileOptions = {
  fromUrl: string;          // URL to download file from
  toFile: string;           // Local filesystem path to save the file to
  headers?: Headers;        // An object of headers to be passed to the server
  background?: boolean;     // Continue the download in the background after the app terminates (iOS only)
  discretionary?: boolean;  // Allow the OS to control the timing and speed of the download to improve perceived performance  (iOS only)
  cacheable?: boolean;      // Whether the download can be stored in the shared NSURLCache (iOS only, defaults to true)
  progressInterval?: number;
  progressDivider?: number;
  begin?: (res: DownloadBeginCallbackResult) => void;
  progress?: (res: DownloadProgressCallbackResult) => void;
  resumable?: () => void;    // only supported on iOS yet
  connectionTimeout?: number // only supported on Android yet
  readTimeout?: number       // supported on Android and iOS
  backgroundTimeout?: number // Maximum time (in milliseconds) to download an entire resource (iOS only, useful for timing out background downloads)
};

옵션을 지정하는 방법은 아래와 같이 downloadFile에 인자로 넣어주는 것이다.

import RNFS from'react-native-fs'
import RNFetchBlob from 'rn-fetch-blob';


const path = RNFetchBlob.fs.dirs.DownloadDir;

const LOCAL_PATH_TO_VIDEO = Platform.OS === 'ios' ? `${RNFS.DocumentDirectoryPath}/${timestamp}.mp4` : `${path}.mp4`

const downloadFileOptions = {
  fromUrl: REMOTE_URI_OF_VIDEO,
  toFile: LOCAL_PATH_TO_VIDEO,
  begin: (res) => console.log(res),
  process: (res) => console.log(res)
}

RNFS.downloadFile(downloadFileOptions)
  .then((res) => {
  console.log('successful video download!')
}).catch((err) => {
  console.error(err.message, err.code)
})

process의 callbackResult는 아래와 같다

type DownloadProgressCallbackResult = {
  jobId: number;          // The download job ID, required if one wishes to cancel the download. See `stopDownload`.
  contentLength: number;  // The total size in bytes of the download resource
  bytesWritten: number;   // The number of bytes written to the file so far
};

위와 같이 사용하면 react-native에서 비디오를 다운로드 할 때 유용하게 사용 할 수 있다.

Refrence

https://github.com/itinance/react-native-fs
https://dev-yakuza.posstree.com/ko/react-native/react-native-fs/

profile
Beyond Code

0개의 댓글