Last active
December 17, 2018 03:20
-
-
Save tsubaki/e1710638022e8f704d873def178a1633 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections; | |
using System.IO; | |
using Unity.Networking; | |
using UnityEngine; | |
using UnityEngine.UI; | |
public class DownloadAndDisplay : MonoBehaviour | |
{ | |
[SerializeField] | |
private string downloadFileURL = "https://user-images.githubusercontent.com/1644563/50053779-1b7a0780-017e-11e9-9736-d88ec4773704.png"; | |
const string saveFilePath = "image.png"; | |
// ファイルの格納先はApplication.persistentDataPathを基準とした相対パスなので、プロパティ作っとく | |
string FilePath { get { return Path.Combine(Application.persistentDataPath, saveFilePath); } } | |
Texture2D texture; | |
private void Awake() | |
{ | |
texture = new Texture2D(2, 2); | |
} | |
private void OnDestroy() | |
{ | |
Destroy(texture); | |
} | |
public void RemoveFile() | |
{ | |
if (File.Exists(FilePath)) | |
File.Delete(FilePath); | |
} | |
public void DownloadStart() | |
{ | |
StartCoroutine(DownloadFileTest()); | |
} | |
IEnumerator DownloadFileTest() | |
{ | |
BackgroundDownloadConfig config = new BackgroundDownloadConfig | |
{ | |
filePath = saveFilePath, | |
url = new Uri(downloadFileURL), | |
policy = BackgroundDownloadPolicy.Default | |
}; | |
// AndroidのPermissionでエラーが出る事があるので、BackgroundDownload.Startはtry-catchで囲いたいけど、 | |
// 開放漏れのほうが怖いのでusingで囲う | |
using (var download = BackgroundDownload.Start(config)) | |
{ | |
yield return download; | |
Debug.Log(download.status); | |
} | |
// ダウンロード完了後に即座に処理を始めるとUI等が更新されず最後の状態で長時間待つ事になる | |
// 事後処理(Zip解答等)があるなら、このタイミングで一旦画面を更新しとくのが良さそう | |
yield return null; | |
// ダウンロード失敗や諸々の要因で読取り失敗するので、try-catchで囲っとく | |
try | |
{ | |
var data = File.ReadAllBytes(FilePath); | |
texture.LoadImage(data, false); | |
GetComponent<RawImage>().texture = texture; | |
} | |
catch (IOException e) { Debug.LogError(e); } | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment