iOS 9.0 또는 macOS 10.11(이상)을 대상으로 하는 Xamarin 앱은 압축 프레임워크를 사용하여 데이터를 압축(인코딩)하고 압축을 해제(디코딩)할 수 있습니다. Xamarin.iOS는 Stream API에 따라 이 프레임워크를 제공합니다. 압축 프레임워크를 사용하면 개발자가 콜백 또는 대리자를 사용할 필요 없이 일반 스트림인 것처럼 압축 및 압축 해제된 데이터와 상호 작용할 수 있습니다.
압축 프레임워크는 다음 알고리즘을 지원합니다.
- LZ4
- LZ4 Raw
- Lzfse
- Lzma
- Zlib
개발자는 압축 프레임워크를 사용하여 타사 라이브러리 또는 NuGets 없이 압축 작업을 수행할 수 있습니다. 이렇게 하면 외부 종속성이 줄어들고 최소 OS 요구 사항을 충족하는 한 모든 플랫폼에서 압축 작업이 지원됩니다.
일반 파일 압축 해제
압축 프레임워크는 Xamarin.iOS 및 Xamarin.Mac에서 스트림 API를 사용합니다. 이 API는 데이터를 압축하기 위해 개발자가 .NET 내의 다른 IO API에 사용되는 일반 패턴을 사용할 수 있음을 의미합니다. 다음 샘플에서는 API에 있는 System.IO.Compression.DeflateStream
API와 유사한 압축 프레임워크를 사용하여 데이터를 압축 해제하는 방법을 보여줍니다.
// sample zlib data
static byte [] compressed_data = { 0xf3, 0x48, 0xcd, 0xc9, 0xc9, 0xe7, 0x02, 0x00 };
using (var backing = new MemoryStream (compressed_data)) // compress data to read
using (var decompressing = new CompressionStream (backing, CompressionMode.Decompress, CompressionAlgorithm.Zlib)) // create decompression stream with the correct algorithm
using (var reader = new StreamReader (decompressing))
{
// perform the required stream operations
Console.WriteLine (reader.ReadLine ());
}
CompressionStream
다른 인터페이스와 마찬가지로 System.IO.Streams
인터페이스를 IDisposable
구현하므로 개발자는 리소스가 더 이상 필요하지 않은 경우 해제되도록 해야 합니다.
일반 파일 압축
또한 압축 API를 사용하면 개발자가 동일한 API를 따라 데이터를 압축할 수 있습니다. 열거자에 명시된 제공된 알고리즘 중 하나를 사용하여 데이터를 압축할 CompressionAlgorithm
수 있습니다.
// sample method that copies the data from the source stream to the destination stream
static void CopyStream (Stream src, Stream dest)
{
byte[] array = new byte[1024];
int bytes_read;
bytes_read = src.Read (array, 0, 1024);
while (bytes_read != 0) {
dest.Write (array, 0, bytes_read);
bytes_read = src.Read (array, 0, 1024);
}
}
static void CompressExample ()
{
// create some sample data to compress
byte [] data = new byte[100000];
for (int i = 0; i < 100000; i++) {
data[i] = (byte) i;
}
using (var dataStream = new MemoryStream (data)) // stream that contains the data to compress
using (var backing = new MemoryStream ()) // stream in which the compress data will be written
using (var compressing = new CompressionStream (backing, CompressionMode.Compress, CompressionAlgorithm.Zlib, true))
{
// copy the data to the compressing stream
CopyStream (dataStream, compressing);
// at this point, the CompressionStream contains all the data from the dataStream but compressed
// using the zlib algorithm
}
비동기 지원
이는 CompressionStream
개발자가 UI 스레드를 차단하지 않고 비동기 키워드(keyword) 사용하여 압축/압축 해제 작업을 수행할 수 있음을 의미하는 모든 비동기 작업을 지원System.IO.DeflateStream
합니다.