What is the most efficient way to validate a compressed ZIP file when using ZIPFoundation

52 Views Asked by At

ZIPFoundation

Is there a method similar to validate that can be used for this purpose?

A method looks like this:

func validateZipFile(at zipFileURL: URL) -> Bool {
    guard let archive = Archive(url: zipFileURL, accessMode: .read) else { return false }
    let validationResult = archive.validate()
    return validationResult == .success
}
1

There are 1 best solutions below

0
Dikey On

ZipUtilities solve the problem.

According to the specification for the .ZIP file format, the end of the central directory record can be used for verification.

NOZUnzipper will perform format validation on a .ZIP file before attempting to unzip it.

- (BOOL)unzipThingsAndReturnError:(out NSError **)error
{
    NSAssert(![NSThread isMainThread]); // do this work on a background thread

    NOZUnzipper *unzipper = [[NOZUnzipper alloc] initWithZipFile:zipFilePath];
    if (![unzipper openAndReturnError:error]) {
        return NO;
    }

    if (nil == [unzipper readCentralDirectoryAndReturnError:error]) {
        return NO;
    }

    __block NSError *enumError = nil;
    [unzipper enumerateManifestEntriesUsingBlock:^(NOZCentralDirectoryRecord * record, NSUInteger index, BOOL * stop) {
        NSString *extension = record.name.pathExtension;
        if ([extension isEqualToString:@"jpg"]) {
            *stop = ![self readImageFromUnzipper:unzipper withRecord:record error:&enumError];
        } else if ([extension isEqualToString:@"json"]) {
            *stop = ![self readJSONFromUnzipper:unzipper withRecord:record error:&enumError];
        } else {
            *stop = ![self extractFileFromUnzipper:unzipper withRecord:record error:&enumError];
        }
    }];

    if (enumError) {
        *error = enumError;
        return NO;
    }

    if (![unzipper closeAndReturnError:error]) {
        return NO;
    }

    return YES;
}

So, it's simple to use NOZUnzipper class to open and read the central directory of a ZIP file.

If any errors occur during this process, function returns false.

func validateZipFile(at zipFileURL: URL) -> Bool {
    let unzipper = NOZUnzipper.init(zipFile: zipFileURL.path)
    do {
        try unzipper.open()
        try unzipper.readCentralDirectory()
    } catch let error{
        return false
    }
    return true
}