Unity용 Cloud Storage로 파일 다운로드

Firebase용 Cloud Storage를 사용하면 Firebase에서 제공하고 관리하는 Cloud Storage 버킷에서 파일을 빠르고 손쉽게 다운로드할 수 있습니다.

참조 만들기

파일을 다운로드하려면 우선 다운로드할 파일을 가리키는 Cloud Storage 참조를 만듭니다.

Cloud Storage 버킷의 루트에 하위 경로를 추가하여 참조를 만들거나 Cloud Storage의 객체를 참조하는 기존 gs:// 또는 https:// URL로 참조를 만들 수 있습니다.

// Create a reference with an initial file path and name
StorageReference pathReference =
    storage.GetReference("images/stars.jpg");

// Create a reference from a Google Cloud Storage URI
StorageReference gsReference =
    storage.GetReferenceFromUrl("gs://bucket/images/stars.jpg");

// Create a reference from an HTTPS URL
// Note that in the URL, characters are URL escaped!
StorageReference httpsReference =
    storage.GetReferenceFromUrl("https://firebasestorage.googleapis.com/b/bucket/o/images%20stars.jpg");

파일 다운로드

참조가 만들어졌으면 4가지 방법으로 Cloud Storage에서 파일을 다운로드할 수 있습니다.

  1. URL에서 다운로드
  2. 바이트 배열로 다운로드
  3. 스트림을 통해 다운로드
  4. 로컬 파일로 다운로드

파일을 검색하는 데 사용할 방법은 게임에서 데이터를 사용하는 방법에 따라 다릅니다.

URL에서 다운로드

Unity의 WWW 또는 UnityWebRequest와 함께 URL을 사용하려면 GetDownloadUrlAsync()을 호출하여 파일의 다운로드 URL을 가져오면 됩니다.

// Fetch the download URL
reference.GetDownloadUrlAsync().ContinueWithOnMainThread(task => {
    if (!task.IsFaulted && !task.IsCanceled) {
        Debug.Log("Download URL: " + task.Result);
        // ... now download the file via WWW or UnityWebRequest.
    }
});

바이트 배열로 다운로드

GetBytesAsync() 메서드를 사용하여 파일을 메모리의 바이트 버퍼로 다운로드할 수 있습니다. 이 메서드는 파일의 전체 콘텐츠를 메모리에 로드합니다. 앱의 가용 메모리보다 큰 파일을 요청하면 앱이 다운됩니다. 메모리 문제를 방지하려면 최대 크기를 앱에서 처리할 수 있는 크기로 설정하거나 다른 다운로드 방법을 사용하세요.

// Download in memory with a maximum allowed size of 1MB (1 * 1024 * 1024 bytes)
const long maxAllowedSize = 1 * 1024 * 1024;
reference.GetBytesAsync(maxAllowedSize).ContinueWithOnMainThread(task => {
    if (task.IsFaulted || task.IsCanceled) {
        Debug.LogException(task.Exception);
        // Uh-oh, an error occurred!
    }
    else {
        byte[] fileContents = task.Result;
        Debug.Log("Finished downloading!");
    }
});

스트림을 통해 다운로드

스트림으로 파일을 다운로드하면 데이터를 로드하면서 동시에 처리할 수 ​​있습니다. 따라서 다운로드를 처리할 때 최대의 유연성을 발휘할 수 있습니다. GetStreamAsync()를 호출하고 자체 스트림 프로세서를 첫 번째 인수로 전달합니다. 백그라운드 스레드에서 스트림과 함께 이 대리자가 호출되므로 디스크에 콘텐츠를 저장하는 경우처럼 지연 시간이 많이 발생하는 작업이나 계산을 수행할 수 있습니다.

// Download via a Stream
reference.GetStreamAsync(stream => {
    // Do something with the stream here.
    //
    // This code runs on a background thread which reduces the impact
    // to your framerate.
    //
    // If you want to do something on the main thread, you can do that in the
    // progress eventhandler (second argument) or ContinueWith to execute it
    // at task completion.
}, null, CancellationToken.None);

GetStreamAsync()는 스트림 프로세서 뒤에 선택적 인수를 사용하여 이 인수로 작업을 취소하거나 진행률에 대한 알림을 받을 수 있습니다.

로컬 파일로 다운로드

GetFileAsync() 메서드는 파일을 로컬 기기로 직접 다운로드합니다. 사용자가 오프라인 상태에서도 파일에 액세스해야 하거나 다른 앱에서 파일을 공유해야 하는 경우 이 방법을 사용하세요.

// Create local filesystem URL
string localUrl = "file:///local/images/island.jpg";

// Download to the local filesystem
reference.GetFileAsync(localUrl).ContinueWithOnMainThread(task => {
    if (!task.IsFaulted && !task.IsCanceled) {
        Debug.Log("File downloaded.");
    }
});

다운로드에 리스너를 연결하여 다운로드 진행률을 모니터링할 수 있습니다. 리스너는 표준 System.IProgress<T> 인터페이스를 따릅니다. StorageProgress 클래스의 인스턴스를 사용하여 자체 Action<T>를 진행 틱의 콜백으로 제공할 수 있습니다.

// Create local filesystem URL
string localUrl = "file:///local/images/island.jpg";

// Start downloading a file
Task task = reference.GetFileAsync(localFile,
    new StorageProgress<DownloadState>(state => {
        // called periodically during the download
        Debug.Log(String.Format(
            "Progress: {0} of {1} bytes transferred.",
            state.BytesTransferred,
            state.TotalByteCount
        ));
    }), CancellationToken.None);

task.ContinueWithOnMainThread(resultTask => {
    if (!resultTask.IsFaulted && !resultTask.IsCanceled) {
        Debug.Log("Download finished.");
    }
});

오류 처리

다운로드 시 오류가 발생하는 이유는 파일이 없는 경우, 사용자에게 파일 액세스 권한이 없는 경우 등 다양합니다. 오류의 자세한 내용은 문서의 오류 처리 섹션을 참조하세요.

다음 단계

Cloud Storage에 저장된 파일의 메타데이터를 가져와서 업데이트할 수도 있습니다.