FetchFileById (Unity)

- Declaration

public static void FetchFileById(string id, Action<string, float> progress, Func<Stream, long, Task> onStreamLoaded)

- Description

Downloads an encrypted file to your device, and provides you with a stream.

Note that at no point in this process does the unencrypted file appear on your device, instead the unencrypted stream is held in memory.

The onStreamLoaded appears odd in the function signature, but in-code it just works as an async callback (see below). The async callback is to give you room to turn this Stream into whatever Unity content you need before it gets garbage collected.

- Sample

using System.IO; using System.Threading.Tasks; using CavrnusSdk.API; using CavrnusSdk.PropertySynchronizers; using UnityEngine; using UnityEngine.UI; namespace CavrnusSdk.UI { public class ImageLoader : MonoBehaviour { [SerializeField] private RawImage rawImage; void Start() { CavrnusFunctionLibrary.AwaitAnySpaceConnection(spaceConn => { spaceConn.BindStringPropertyValue(GetComponent<CavrnusPropertiesContainer>().UniqueContainerName, "ContentId", FetchImage); }); } private void FetchImage(string file) { if(destroyed) //Were we removed during the previous load step? return; //We probably get this before we get the actual ContentId if (file == null) return; Debug.Log("Fetching " + file); CavrnusFunctionLibrary.FetchFileById(file, (step, prog) => Debug.Log($"Downloading: {step} - {(int)(prog*100)}% "), async (stream, len) => { Debug.Log("Fetched " + file); if (destroyed) //Were we removed during the previous load step? return; await LoadImage(stream, len); }); } private async Task LoadImage(Stream stream, long len) { var texture = new Texture2D(1, 1); var imageData = new byte[len]; await stream.ReadAsync(imageData, 0, (int)len); texture.LoadImage(imageData); rawImage.texture = texture; } private bool destroyed = false; private void OnDestroy() { destroyed = true; } } }