Giter Club home page Giter Club logo

lzmasdkobjc's Introduction

Deprecation

This lib/pod is no longer supported, but has a successor: PLzmaSDK.

For all Apple platforms, the PLzmaSDK is available for Swift & Objective-C via CocoaPods and Swift Package Manager.

LzmaSDKObjC

Platform Version License

Tier badge

It's not yet another wrapper around C part of the LZMA SDK with all it's limitations.
Based on C++ LZMA SDK version 19.00 (1900 - latest for now) and patched for iOS & Mac OS platforms.
Can be used with Swift and Objective-C.

Description


It's not yet another wrapper around C part of the LZMA SDK with all it's limitations. Based on C++ LZMA SDK version 19.00 (1900 - latest for now) and patched for iOS & Mac OS platforms.

The main advantages is:

  • List, extract 7z files (Lzma & Lzma2 compression method).
  • List, extract encrypted (password protected) 7z files (Lzma & Lzma2 compression method).
  • List, extract encrypted (password protected) + encrypted header (no visible content, files list, without password) 7z files (Lzma & Lzma2 compression method).
  • Create 7z archives (Lzma & Lzma2 compression method).
  • Create encrypted (password protected) 7z archives (Lzma & Lzma2 compression method).
  • Create encrypted (password protected) + encrypted header (no visible content, files list, without password) 7z archives (Lzma & Lzma2 compression method).
  • Manage memory allocations during listing/extracting. See below section: Tune up speed, performance and disk IO operations.
  • Tuned up for using less than 500Kb for listing/extracting, can be easily changed at runtime (no hardcoded definitions). See below section: Tune up speed, performance and disk IO operations.
  • Manage IO read/write operations, also can be easily changed at runtime (no hardcoded definitions). See below section: Tune up speed, performance and disk IO operations.
  • Track smoothed progress.
  • Support reading and extracting archive files with size more than 4GB.
  • UTF8 support.
  • Extra compression/decompression functionality of single NSData object with Lzma2.

Installation with CocoaPods

Podfile

use_frameworks!
platform :ios, '9.0'

target '<REPLACE_WITH_YOUR_TARGET>' do
    pod 'LzmaSDK-ObjC', :inhibit_warnings => true
end

Use frameworks (dynamic linking) to include Lzma codecs code in your application.

Example Swift and Objective-C


List and extract

Create and setup reader with archive path and/or archive type, optionaly delegate and optionaly password getter block, in case of encrypted archive
Swift
import LzmaSDK_ObjC
...

// select full path to archive file with 7z extension
let archivePath = "path to archive"

// 1.1 Create reader object.
let reader = LzmaSDKObjCReader(fileURL: NSURL(fileURLWithPath: archivePath)
// 1.2 Or create with predefined archive type if path doesn't containes suitable extension
let reader = LzmaSDKObjCReader(fileURL: NSURL(fileURLWithPath: archivePath), andType: LzmaSDKObjCFileType7z)

// Optionaly: assign delegate for tracking extract progress.
reader.delegate = self

// If achive encrypted - define password getter handler.
// NOTES:
// - Encrypted file needs password for extract process.
// - Encrypted file with encrypted header needs password for list(iterate) and extract archive items.
reader.passwordGetter = {
	return "password to my achive"
}
...

// Delegate extension
extension ReaderDelegateObject: LzmaSDKObjCReaderDelegate {
	func onLzmaSDKObjCReader(reader: LzmaSDKObjCReader, extractProgress progress: Float) {
		print("Reader progress: \(progress) %")
	}
}
Objective-C
// Select full path to archive file with 7z extension.
NSString * archivePath = <path to archive>;

// 1.1 Create and hold strongly reader object.
self.reader = [[LzmaSDKObjCReader alloc] initWithFileURL:[NSURL fileURLWithPath:archivePath]];
// 1.2 Or create with predefined archive type if path doesn't containes suitable extension
self.reader = [[LzmaSDKObjCReader alloc] initWithFileURL:[NSURL fileURLWithPath:archivePath]
						 andType:LzmaSDKObjCFileType7z];

// Optionaly: assign weak delegate for tracking extract progress.
_reader.delegate = self;

// If achive encrypted - define password getter handler.
// NOTES:
// - Encrypted file needs password for extract process.
// - Encrypted file with encrypted header needs password for list(iterate) and extract archive items.
_reader.passwordGetter = ^NSString*(void){
	return @"password to my achive";
};
Open archive, e.g. find out type of achive, locate decoder and read archive header
Swift
// Try open archive.
do {
	try reader.open()
}
catch let error as NSError {
	print("Can't open archive: \(error.localizedDescription) ")
}
Objective-C
// Open archive, with or without error. Error can be nil.
NSError * error = nil;
if (![_reader open:&error]) {
	NSLog(@"Open error: %@", error);
}
NSLog(@"Open error: %@", _reader.lastError);
Iterate archive items, select and store required items for future processing
Swift
var items = [LzmaSDKObjCItem]()  // Array with selected items.
// Iterate all archive items, track what items do you need & hold them in array.
reader.iterateWithHandler({(item: LzmaSDKObjCItem, error: NSError?) -> Bool in
	items.append(item) // If needed, store to array.
	return true // true - continue iterate, false - stop iteration
})
Objective-C
NSMutableArray * items = [NSMutableArray array]; // Array with selected items.
// Iterate all archive items, track what items do you need & hold them in array.
[_reader iterateWithHandler:^BOOL(LzmaSDKObjCItem * item, NSError * error){
	NSLog(@"\n%@", item);
	if (item) [items addObject:item]; // If needed, store to array.
	return YES; // YES - continue iterate, NO - stop iteration
}];
NSLog(@"Iteration error: %@", _reader.lastError);
Extract or test archive items
Swift
// Extract selected items from prev. step.
// true - create subfolders structure for the items.
// false - place item file to the root of path(in this case items with the same names will be overwrited automaticaly).
if reader.extract(items, toPath: "/Volumes/Data/1/", withFullPaths: true) {
	print("Extract failed: \(reader.lastError?.localizedDescription)")
}

// Test selected items from prev. step.
if reader.test(items) {
	print("Test failed: \(reader.lastError?.localizedDescription)")
}
Objective-C
// Extract selected items from prev. step.
// YES - create subfolders structure for the items.
// NO - place item file to the root of path(in this case items with the same names will be overwrited automaticaly).
[_reader extract:items
          toPath:@"/extract/path"
    withFullPaths:YES]; 
NSLog(@"Extract error: %@", _reader.lastError);

// Test selected items from prev. step.
[_reader test:items];
NSLog(@"test error: %@", _reader.lastError);
Create 7z archive
Swift
// Create writer
let writer = LzmaSDKObjCWriter(fileURL: NSURL(fileURLWithPath: "/Path/MyArchive.7z"))

// Add file data's or paths
writer.addData(NSData(...), forPath: "MyArchiveFileName.txt") // Add file data
writer.addPath("/Path/somefile.txt", forPath: "archiveDir/somefile.txt") // Add file at path
writer.addPath("/Path/SomeDirectory", forPath: "SomeDirectory") // Recursively add directory with all contents

// Setup writer
writer.delegate = self // Track progress
writer.passwordGetter = { // Password getter
	return "1234"
}

// Optional settings 
writer.method = LzmaSDKObjCMethodLZMA2 // or LzmaSDKObjCMethodLZMA
writer.solid = true
writer.compressionLevel = 9
writer.encodeContent = true
writer.encodeHeader = true
writer.compressHeader = true
writer.compressHeaderFull = true
writer.writeModificationTime = false
writer.writeCreationTime = false
writer.writeAccessTime = false

// Open archive file
do {
	try writer.open()
} catch let error as NSError {
	print(error.localizedDescription)
}

// Write archive within current thread
writer.write()

// or
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)) {
	writer.write()
}
Objective-C
// Create writer
LzmaSDKObjCWriter * writer = [[LzmaSDKObjCWriter alloc] initWithFileURL:[NSURL fileURLWithPath:@"/Path/MyArchive.7z"]];

// Add file data's or paths
[writer addData:[NSData ...] forPath:@"MyArchiveFileName.txt"]; // Add file data
[writer addPath:@"/Path/somefile.txt" forPath:@"archiveDir/somefile.txt"]; // Add file at path
[writer addPath:@"/Path/SomeDirectory" forPath:@"SomeDirectory"]; // Recursively add directory with all contents

// Setup writer
writer.delegate = self; // Track progress
writer.passwordGetter = ^NSString*(void) { // Password getter
	return @"1234";
};

// Optional settings 
writer.method = LzmaSDKObjCMethodLZMA2; // or LzmaSDKObjCMethodLZMA
writer.solid = YES;
writer.compressionLevel = 9;
writer.encodeContent = YES;
writer.encodeHeader = YES;
writer.compressHeader = YES;
writer.compressHeaderFull = YES;
writer.writeModificationTime = NO;
writer.writeCreationTime = NO;
writer.writeAccessTime = NO;

// Open archive file
NSError * error = nil;
[writer open:&error];

// Write archive within current thread
[writer write];

// or
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
	[writer write];
});
Compress/decompress single data buffer
Swift
// Compress data with compression maximum compression ratio.
let compressedData = LzmaSDKObjCBufferCompressLZMA2(sourceData, 1)
// Decompress previvously compressed data.
let decompressedData = LzmaSDKObjCBufferDecompressLZMA2(compressedData)
Objective-C
// Compress data with compression maximum compression ratio.
NSData * compressedData = LzmaSDKObjCBufferCompressLZMA2(sourceData, 1);
// Decompress previvously compressed data.
NSData * decompressedData = LzmaSDKObjCBufferDecompressLZMA2(compressedData);

Tune up speed, performance and disk IO operations


Original C++ part of the LZMA SDK was patched to have a possibility to tune up default(hardcoded) settings. For list and extract functionality was defined next global variables: kLzmaSDKObjCStreamReadSize, kLzmaSDKObjCStreamWriteSize, kLzmaSDKObjCDecoderReadSize and kLzmaSDKObjCDecoderWriteSize. This variables holds size values in bytes, so, for the single reader object summary of this 4's values will be allocated.

Keep in mind: operations with memory much more faster than disk IO operations, so read below situations:

switch (<what do I need ?>) {
	case <I need faster list and extract>:
		//TODO: Increase stream and decoder size of buffers
		Result:
			1. more allocated memory
			2. less IO read/write operations and less delays
			3. less smoothed progress
			4. more CPU load (do a job, not distracted to read/write data)
		break;

	case <I need use less memory or more smoothed progress>:
		//TODO: Decrease stream and decoder size of buffers
		Result:
			1. less allocated memory
			2. more IO read/write operations and more delays
			3. more smoothed progress
			4. less CPU load (wait for read/write data)
		break;

	default:
		//TODO: use current settings
		break;
	};

NOTE: Modify global variables before creating & using reader object.

NOTE: This allocation sizes doesn't affet to memory allocated for the archive dictionary.

Features list (TODO/DONE)


  • Lzma/*.7z
    • List
      • Regular archive. tests/files/lzma.7z
      • Encrypted archive with AES256. tests/files/lzma_aes256.7z
      • Encrypted archive + encrypted header(no visible content, files list, without password) with AES256. tests/files/lzma_aes256_encfn.7z
    • Extract
      • Regular archive. tests/files/lzma.7z
      • Encrypted archive with AES256. tests/files/lzma_aes256.7z
      • Encrypted archive + encrypted header(no visible content, files list, without password) with AES256. tests/files/lzma_aes256_encfn.7z
    • Create
      • Regular archive.
      • Encrypted archive with AES256.
      • Encrypted archive + encrypted header(no visible content, files list, without password) with AES256.
  • Lzma2/*.7z
    • List
      • Regular archive. tests/files/lzma2.7z
      • Encrypted archive with AES256. tests/files/lzma2_aes256.7z
      • Encrypted archive + encrypted header(no visible content, files list, without password) with AES256. tests/files/lzma2_aes256_encfn.7z
    • Extract
      • Regular archive. tests/files/lzma2.7z
      • Encrypted archive with AES256. tests/files/lzma2_aes256.7z
      • Encrypted archive + encrypted header(no visible content, files list, without password) with AES256. tests/files/lzma2_aes256_encfn.7z
    • Create
      • Regular archive.
      • Encrypted archive with AES256.
      • Encrypted archive + encrypted header(no visible content, files list, without password) with AES256.
  • Omit unused code, reduce buildable, original code size.

License


By using this all you are accepting original LZMA SDK and MIT license (see below):

The MIT License (MIT)

Copyright (c) 2015 - 2020 Oleh Kulykov [email protected]

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

lzmasdkobjc's People

Contributors

enefry avatar jakubvano avatar olehkulykov avatar rhotta avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

lzmasdkobjc's Issues

Extracting item from archive to NSData object (without saving it to disk)

Hello,
This library is the best available for iOS in term of archiving unarchiving protected files.
It will be good to add additional features that would make it even better:

In certain scenarios extracting a file to disk and then reading it back into NSData is too cumbersome, specially when the only thing that is needed is to process the NSData.
It will be good to have the ability to extract an item from an archive directly as NSData.
Is that something that is possible?

Unarchive .7z file works randomly - LZMA DEBUG 72: ERROR: code = 1,

Hi,

I am trying to download file and unarchive it in my app. The problem is that sometimes Lzma works perfectly but most of the time I am getting this error in console:

LZMA DEBUG 72: ERROR: code = 1, file = '/Users/piotrek/Development/zarazjade_mac/Pods/LzmaSDK-ObjC/src/LzmaSDKObjCFileDecoder.cpp', line = 146, description = Can't open archive file with result: 1
Can't open archive: Can't open archive file with result: 1

There is a code that unzip my file:

guard let fileURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else { return }
let reader = LzmaSDKObjCReader(fileURL: fileURL.appendingPathComponent(lastFile.name), andType: LzmaSDKObjCFileType7z)
reader.delegate = self
reader.passwordGetter = {
   return ""
}
do {
   try reader.open()
                            
   var items = [LzmaSDKObjCItem]()
   reader.iterate(handler: { (item, error) -> Bool in
     items.append(item)
      return true
   })
                            
   if reader.extract(items, toPath: "/Users/piotrek/Documents/", withFullPaths: true) {
      print("Extract failed: \(reader.lastError?.localizedDescription)")
   }
                            
} catch let error as NSError {
   print("Can't open archive: \(error.localizedDescription) ")
}

I will be glad for help.

7z archive creation support?

Howdy - I see that support for creating and updating 7z archives is on your roadmap. Curious if there's an ETA for this functionality?

Thanks!

About 7z-MultiVolume

when i open the { #define _7Z_VOL } in the 7zHeader.h, i got some error, can you help me to fix the
error, i want to make 7z multi-volume archives on the mobile devices, thanks very much.

use_frameworks!

Is it possible to use it under a purely static library project?

Ppmd codec

Hi,
I've statically linked the repo to my project, by adding files in podspec file:

  1. In LzmaSDKObjCReader.mm resetting prop variable using { 0 } is not possible in c, so I got error. I searched in stackoverflow and resolved this by replacing { 0 } with PROPVARIANT(). Another way is to declare PROPVARIANT emptyProp = { 0 }; and resetting prop variable by setting to emptyProp, or declare different variables for each part.

  2. I've found out Ppmd (de)coder files aren't added to pods (and I didn't added so), consequently I couldn't extract Ppmd test file. I've added this files and resolved the problem

  3. I've also added ByteSwap, Copy and Bcj2 (de)coder files. Only had an small issue in Bcj2Enc.c file which resolved by commenting #include <windows.h>

Extract zip data from nsdata

Hello ,

I have a base64 string which I am converting to nsdata and that nsdata is in 7zip format , I want to decompress the data using LzmaSDKObjCBufferDecompressLZMA2 function but I am not able to decompress it . my result is always 0 bytes .

can you point me to correct direction

Compile error in 'lzma/cpp/windows/FileName.cpp'

I've found error ['IsAbsolutePath' is missing exception specification 'throw()'] and ['GetRootPrefixSize' is missing exception specification 'throw()'] while compiling file 'lzma/cpp/windows/FileName.cpp'. It seems this file has been removed from master branch but cocoapod somehow still retrieve it.

"No suitable decoder found."

Using the sample code, with a valid .7z file, I get the message:

Open error: Error Domain=LzmaSDKObjCReader Code=-1 "No suitable decoder found."

Running on iOS 9.1, Xcode 7.1.1.

Seems to be because CreateObject is not returning S_OK, I couldn't get further than this though?

pass through not supported

Seems to fail out on uncompressed archives. My project has about 15 gigabytes of data that needs to be zipped and transferred. This data is image related and encrypted already. I was getting failures with kUnsupportedMethod when running in pass-through mode (-mx0) while compressing. The solution for now at least for me is to compress my archives, but compressing 15 gigabytes of encrypted data takes hours instead of a couple of minutes in pass through.

It would seem to be a trivial case to add "no compression" as an available compression method. From what I can tell it has to be explicitly compressed with LZMA or LZMA2 for this kit to work.

check .7z is encrypted

how can I check .7z file has encrypted.
I try this way

var items = [LzmaSDKObjCItem]()
        reader.iterate { (item: LzmaSDKObjCItem, error: Error?) -> Bool in
            print(item.isEncrypted)
            items.append(item)
            return true
        }

but its not work,
the item cannot be read because the password is incorrect.
So I want to make sure that the file has a password, and if it does, I'll prompt the user for a password
Hope to get your answer

Encrypt and decrypt in memory

Привет! Спасибо за библиотеку. Есть вопрос: как можно реализовать сжатие и экстракт сразу в память? Т.е. хочется использовать что-то по типу
LzmaSDKObjCWriter * writer = [[LzmaSDKObjCWriter alloc] initWithBuffer: ]];
Чтобы я мог указать степень сжатия и шифрование контента

Reader.extract should only extract the specified items

When following the example Swift in the ReadMe, I've noticed that reader.extract, rather than extracting only the specified items, appears to incorrectly extract items that were not specified.

I observe that the incorrectly extracted items, appear to be those items that precede the specified items in the archive.

Being unable to install in a objc project, no swift inside.

I am being unable to add this SDK to my project, I added the pod and run pod install but when trying to call reader open I am getting following warning in the console:

LZMA DEBUG 85: ERROR REASON: - Unsupported archive GUID.

  • Codec was not compiled in or stripped by static linking. Make sure you are using 'use_frameworks!' and/or dynamic linking.

Is there anything else than only adding the pod necessary to be able to run this? I am also not sure about following line in the documentation about "Installation":

Use frameworks (dynamic linking) to include Lzma codecs code in your application.

Does this mean that use_frameworks! MUST be added to the pod file in order for this SDK to work?

Swift compiler warnings (Xcode 10.1, Swift 4.2)

Hello,

I am using LzmaSDKObjC via Cocoapods in a Swift project. While the code works fine, the Swift Compiler is throwing up the following warnings:

/LzmaSDK-ObjC/LzmaSDK_ObjC.framework/Headers/LzmaSDKObjCWriter.h:212:1: warning: conflicting nullability specifier on return types, 'nullable' conflicts with existing specifier 'nonnull'
- (nullable instancetype) init NS_UNAVAILABLE;

LzmaSDK-ObjC/LzmaSDK_ObjC.framework/Headers/LzmaSDKObjCWriter.h:213:1: warning: conflicting nullability specifier on return types, 'nullable' conflicts with existing specifier 'nonnull'
+ (nullable instancetype) new NS_UNAVAILABLE;

LzmaSDK-ObjC/LzmaSDK_ObjC.framework/Headers/LzmaSDKObjCReader.h:162:1: warning: conflicting nullability specifier on return types, 'nullable' conflicts with existing specifier 'nonnull'
- (nullable instancetype) init NS_UNAVAILABLE;

LzmaSDK-ObjC/LzmaSDK_ObjC.framework/Headers/LzmaSDKObjCReader.h:163:1: warning: conflicting nullability specifier on return types, 'nullable' conflicts with existing specifier 'nonnull'
+ (nullable instancetype) new NS_UNAVAILABLE;

Thanks!

Extraction of one item in continuous archive leads to extraction of all items

Привет! Большое спасибо за библиотеку. Столкнулся со следующей проблемой:
пытаюсь распаковать один файл в непрерывном архиве, но в результате получаю не только этот файл, но и все те, которые находились перед ним.

Мой код:

    NSURL *url = [NSURL fileURLWithPath:@"/Users/Admin/Desktop/1.7z"];
    LzmaSDKObjCReader *lzmaArch = [[LzmaSDKObjCReader alloc] initWithFileURL:url];
    if (![lzmaArch open:nil])
        return;
    
    __block NSError *iterateError;
    NSMutableArray *items = [[NSMutableArray alloc] init];
    [lzmaArch iterateWithHandler:^BOOL(LzmaSDKObjCItem * item, NSError *error)
     {
         if (error)
             iterateError = error;
         
         [items addObject:item];
         return error == nil;
     }];
    
    if (iterateError)
        return;
    
    // извлекаем только 5й LzmaSDKObjCItem, но по факту извлекутся первые 5
    [lzmaArch extract:@[items[4]] toPath:@"/Users/Admin/Desktop" withFullPaths:NO];

Проблемный файл пришлось дополнительно запаковать в zip, так как Github не поддерживает прикрепление .7z
1.7z.zip

С обычными архивами таких проблем, разумеется, нет - извлекает только указанный item.

an't create archive object file type: 1

ERROR: code = -1, file = '/Users/xxx/Desktop/LzmaSDKObjC-0.0.8/src/LzmaSDKObjCFileDecoder.cpp', line = 185, description = Can't create archive object file type: 12016-03-28 17:53:04:357 TaeExam[3465:668038] Open error: Error Domain=LzmaSDKObjCReader Code=-1 "Can't create archive object file type: 1" UserInfo={code=-1, line=185, file=/Users/xxx/Desktop/LzmaSDKObjC-0.0.8/src/LzmaSDKObjCFileDecoder.cpp, NSLocalizedDescription=Can't create archive object file type: 1}

Архив с папками не распаковывается вовсе или частично.

BOOL Done = [reader extract:items toPath:destionation withFullPaths:YES];

Done всегда NO; и ничего не распаковывает.

Если withFullPaths:NO то Done тоже NO, при этом распаковывает, но все файлы из папок кидает в одну.

Тестил на этом файле
http://files.d-lan.dp.ua/download.php?file=a2b9d437ea26b638e7b2b7df99e1cf8f

Encounter error SZ_ERROR_INPUT_EOF

The code is as below:

    pucCompressedData = new unsigned char[MAX_COMPRESS_DATA];
    p_pTargetImgPtr = new unsigned char[MAX_COMPRESS_DATA];
    szOutProps = new unsigned char[5];
    
    
    iLzmaCompressionStatus = LzmaCompress(pucCompressedData, (size_t *)&uiCompressedDataSize,
                                          pucBuffer, iTempFileSize,
                                          szOutProps, (size_t *)&uiOutPropsSize,
                                          iLevel,
                                          uiDict_size,
                                          iLc,
                                          iLp,
                                          iPb,
                                          iFb,
                                          iNumThreads);

    uiUncompressedDataSize = SZ-1;
    
    int iLzmaUncompressStatus = LzmaUncompress(
                                               /* 1 */ p_pTargetImgPtr,
                                               /* 2 */ (size_t*)&uiUncompressedDataSize,
                                               /* 3 */ pucCompressedData,
                                               /* 4 */ (size_t*)&uiCompressedDataSize,
                                               /* 5 */ szOutProps,
                                               /* 6 */ (size_t)uiOutPropsSize);

Compress file in iOS and decompress in Java

Hi, I want to transfer a file from an Ipad to an Java web application.

In iOS I use the LzmaSDKObjCBufferCompressLZMA2 to compress the file content:

if let data = NSData(contentsOfFile: pathToFile)
{
if let compress = LzmaSDKObjCBufferCompressLZMA2(data, 0)
{
compress.writeToFile(backupPath, atomically: true)
}
}

But on server side neither decompressor (XZ utils, Apache Commons Compressor) is able to detect the file content as valid format.

So my question is: What do I have to do in order to save a valid LZMA(2) compressed file that can be decompressed by those libraries?

Log spam in DEBUG

There are a ton of log messages in DEBUG. Would it be OK to add a way to turn that off, even in DEBUG mode?

Open error: Error Domain=LzmaSDKObjCReader Code=-1 "Can't create archive object file type: 1" UserInfo={code=-1, NSLocalizedDescription=Can't create archive object file type: 1, file=/Users/kjx/XHWorkStation/XHEnglishBrushStudent/Pods/LzmaSDK-ObjC/src/LzmaSDKObjCFileDecoder.cpp, line=185}

Open error: Error Domain=LzmaSDKObjCReader Code=-1 "Can't create archive object file type: 1" UserInfo={code=-1, NSLocalizedDescription=Can't create archive object file type: 1, file=/Users/kjx/XHWorkStation/XHEnglishBrushStudent/Pods/LzmaSDK-ObjC/src/LzmaSDKObjCFileDecoder.cpp, line=185}

Can't create archive object file type: 1

ERROR: code = -1, file = '/Users/xxx/Desktop/LzmaSDKObjC-0.0.8/src/LzmaSDKObjCFileDecoder.cpp', line = 185, description = Can't create archive object file type: 12016-03-28 17:53:04:357 TaeExam[3465:668038] Open error: Error Domain=LzmaSDKObjCReader Code=-1 "Can't create archive object file type: 1" UserInfo={code=-1, line=185, file=/Users/xxx/Desktop/LzmaSDKObjC-0.0.8/src/LzmaSDKObjCFileDecoder.cpp, NSLocalizedDescription=Can't create archive object file type: 1}

I‘m use static Libray,LzmaSDKObjC-0.0.8,

LzmaSDKObjCExtractCallback.mm have some problem!

When i use function

  • (BOOL) extract:(nullable NSArray<LzmaSDKObjCItem *> *) items
    toPath:(nullable NSString *) path
    withFullPaths:(BOOL) isFullPaths

like this

[reader extract:items
         toPath:deleteLastpath
  withFullPaths:YES];

It isn't giving dictionary.

I found "LzmaSDKObjCExtractCallback.mm" line 105 "subPath" is wrong.

It is ok. As follows:

NSString * subPathNew =[fullPath stringByAppendingString: subPath];
if ([manager fileExistsAtPath:subPathNew isDirectory:&isDir]) {
if (!isDir) {
this->setLastError(E_ABORT, LINE, FILE, "Destination path: [%s] exists in directory: [%s] and it's file", [subPath UTF8String], [fullPath UTF8String]);
return E_ABORT;
}
} else if (![manager createDirectoryAtPath:subPathNew withIntermediateDirectories:YES attributes:nil error:&error] || error) {
this->setLastError(E_ABORT, LINE, FILE, "Can't create subdirectory: [%s] in directory: [%s]", [subPath UTF8String], [fullPath UTF8String]);
return E_ABORT;
}

crash breakdown

LZMA DEBUG 72: ERROR: code = -1, file = '/Users/X/Desktop/testLzma/Pods/LzmaSDK-ObjC/src/LzmaSDKObjCBaseCoder.cpp', line = 50, description = Can't create archive object file type: 1
LZMA DEBUG 85: ERROR REASON: - Unsupported archive GUID.

  • Codec was not compiled in or stripped by static linking. Make sure you are using 'use_frameworks!' and/or dynamic linking.
    2017-03-23 11:20:59.326 testLzma[70187:4145611] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[__NSArrayM insertObject:atIndex:]: object cannot be nil'

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.