abbeycode/UnrarKit
Acerca de
Easily read RAR archives on Mac and iOS
Desarrollo web y de aplicacionesCrecimiento de estrellas medido
- in 24h
- 0
- in 7 days
- 0
- in 15 days
- 0
- in 1 month
- Recopilando historial
Cambios netos en períodos que se solapan, no totales diarios. Los datos no disponibles se dejan en blanco. Las estrellas indican interés, no calidad.
README.md
OriginalAbout
UnrarKit lets macOS, iOS, Mac Catalyst, and visionOS apps read RAR archives. It is currently based on version 7.3.2 (7.30 beta 2) of the UnRAR library.
There is a main project, with unit tests, and a basic iOS example project, which demonstrates how to use the library. To see all of these, open the main workspace file.
I'm always open to improvements, so please submit your pull requests, or create issues for someone else to implement.
Installation
UnrarKit 2.10 was the final release published to CocoaPods. The last beta published there was 2.10-beta8. For 2.11, including 2.11.0-beta1, use Swift Package Manager or Carthage.
UnrarKit 2.11 supports macOS 12.0+, iOS 15.0+, Mac Catalyst 15.0+, and visionOS 1.0+.
Swift Package Manager
In Xcode, choose File > Add Package Dependencies…, enter https://github.com/abbeycode/UnrarKit.git, and add the UnrarKit product to your target. Select the v2.11 branch. To use a local checkout, choose Add Local… and select the repository directory.
To use a neighboring checkout from another Package.swift, add .package(path: "../UnrarKit") to the package dependencies and .product(name: "UnrarKit", package: "UnrarKit") to your target's dependencies.
The package requires Swift tools 6.2 or later. In Swift, import the module and open a RAR file by URL.
import UnrarKit
let archive = try URKArchive(url: archiveURL)
let filenames = try archive.listFilenames()
Carthage
Add UnrarKit to your Cartfile.
github "abbeycode/UnrarKit" "v2.11"
Run carthage update UnrarKit --use-xcframeworks. If your Cartfile pins a release, carthage bootstrap --use-xcframeworks --no-use-binaries builds it from source with the same version and build number as the published XCFramework. Add Carthage/Build/UnrarKit.xcframework to your app target and select Embed & Sign.
For Mac Catalyst, use the Swift package or the release XCFramework. To build the XCFramework locally from the current commit, run ./Scripts/archive-carthage.sh. The resulting UnrarKit.xcframework.zip includes Mac Catalyst for Apple silicon and Intel.
For a native visionOS app, use Swift Package Manager, the release XCFramework, or build from source with carthage update UnrarKit --use-xcframeworks --platform visionOS. The XCFramework includes separate slices for Apple Vision Pro and the visionOS Simulator.
If you’re upgrading from 2.10, replace the old Carthage/Build/Mac/UnrarKit.framework or Carthage/Build/iOS/UnrarKit.framework reference. Remove the old UnrarKit entry from any carthage copy-frameworks phase and its input and output file lists.
Privacy manifest
Swift Package Manager and Carthage both include PrivacyInfo.xcprivacy. UnrarKit collects no data and does no tracking. It reads file metadata during archive operations in app containers (C617.1) and in locations the user grants access to (3B52.1). UnrarKit does not query available disk space.
Example Usage
NSError *archiveError = nil;
URKArchive *archive = [[URKArchive alloc] initWithPath:@"An Archive.rar" error:&archiveError];
NSError *error = nil;
Listing the file names in an archive
NSArray<String*> *filesInArchive = [archive listFilenames:&error];
for (NSString *name in filesInArchive) {
NSLog(@"Archived file: %@", name);
}
Listing the file details in an archive
NSArray<URKFileInfo*> *fileInfosInArchive = [archive listFileInfo:&error];
for (URKFileInfo *info in fileInfosInArchive) {
NSLog(@"Archive name: %@ | File name: %@ | Size: %lld", info.archiveName, info.filename, info.uncompressedSize);
}
Working with passwords
NSArray<URKFileInfo*> *fileInfosInArchive = [archive listFileInfo:&error];
if (archive.isPasswordProtected) {
NSString *givenPassword = // prompt user
archive.password = givenPassword
}
// You can now extract the files
Extracting files to a directory
BOOL extractFilesSuccessful = [archive extractFilesTo:@"some/directory"
overWrite:NO
error:&error];
Extracting a file into memory
NSData *extractedData = [archive extractDataFromFile:@"a file in the archive.jpg"
error:&error];
Streaming a file
For large files, you may not want the whole contents in memory at once. You can handle it one "chunk" at a time, like so:
BOOL success = [archive extractBufferedDataFromFile:@"a file in the archive.jpg"
error:&error
action:
^(NSData *dataChunk, CGFloat percentDecompressed) {
NSLog(@"Decompressed: %f%%", percentDecompressed);
// Do something with the NSData chunk
}];
Progress Reporting
The following methods support NSProgress and NSProgressReporting:
extractFilesTo:overwrite:error:extractData:error:extractDataFromFile:error:performOnFilesInArchive:error:performOnDataInArchive:error:extractBufferedDataFromFile:error:action:
Using implicit NSProgress hierarchy
You can create your own instance of NSProgress and observe its fractionCompleted property with KVO to monitor progress like so:
static void *ExtractDataContext = &ExtractDataContext;
URKArchive *archive = [[URKArchive alloc] initWithURL:aFileURL error:nil];
NSProgress *extractDataProgress = [NSProgress progressWithTotalUnitCount:1];
[extractDataProgress becomeCurrentWithPendingUnitCount:1];
NSString *observedSelector = NSStringFromSelector(@selector(fractionCompleted));
[extractDataProgress addObserver:self
forKeyPath:observedSelector
options:NSKeyValueObservingOptionInitial
context:ExtractDataContext];
NSError *extractError = nil;
NSData *data = [archive extractDataFromFile:firstFile error:&extractError];
[extractDataProgress resignCurrent];
[extractDataProgress removeObserver:self forKeyPath:observedSelector];
Using your own explicit NSProgress instance
If you don't have a hierarchy of NSProgress instances, or if you want to observe more details during progress updates in extractFilesTo:overwrite:error:, you can create your own instance of NSProgress and set the URKArchive instance's progress property, like so:
static void *ExtractFilesContext = &ExtractFilesContext;
URKArchive *archive = [[URKArchive alloc] initWithURL:aFileURL error:nil];
NSProgress *extractFilesProgress = [NSProgress progressWithTotalUnitCount:1];
archive.progress = extractFilesProgress;
NSString *observedSelector = NSStringFromSelector(@selector(localizedDescription));
[self.descriptionsReported removeAllObjects];
[extractFilesProgress addObserver:self
forKeyPath:observedSelector
options:NSKeyValueObservingOptionInitial
context:ExtractFilesContext];
NSError *extractError = nil;
BOOL success = [archive extractFilesTo:extractURL.path
overwrite:NO
error:&extractError];
[extractFilesProgress removeObserver:self forKeyPath:observedSelector];
Cancellation with NSProgress
Using either method above, you can call [progress cancel] to stop the operation in progress. It will cause the operation to fail, returning nil or NO (depending on the return type, and give an error with error code URKErrorCodeUserCancelled.
Notes
To open in Xcode, use the UnrarKit.xcworkspace file, which includes the other projects.
The example app
Included in the source repo is a project named "UnrarExample", that builds as part of the main solution. It's only ever verified to run in the simulator, but if you provide Team info, it should probably also run on-device.
For large file extraction, the tool uses the rar executable. You may need to right-click and open it in Finder to get through Gatekeeper the first time you do so.
Documentation
The public headers document archive operations and file metadata. URKArchive.h · URKFileInfo.h
Logging
UnrarKit uses Apple's unified logging system for logging and activity tracing. View messages at the Info or Debug level for details about an operation, or use activity tracing to follow the calls that led to an error. Apple logging documentation
When debugging your own code, if you'd like to decrease the verbosity of the UnrarKit framework, you can run the following command:
sudo log config --mode "level:default" --subsystem com.abbey-code.UnrarKit
The available levels, in order of increasing verbosity, are default, info, debug, with debug being the default.
Logging guidelines
These are the general rules governing the particulars of how activities and log messages are classified and written. They were written after the initial round of log messages were, so there may be some inconsistencies (such as an incorrect log level). If you think you spot one, open an issue or a pull request!
Logging
Log messages should follow these conventions.
- Log messages don't have final punctuation (like these list items)
- Messages that note a C function is about to be called, rather than a higher level UnrarKit or Cocoa method, end with "...", since it's not expected for them to log any details of their own
Default log level
There should be no messages at this level, so that it's possible for a consumer of the API to turn off all diagnostic logging from it, as detailed above. It's only possible to log config --mode "level:off" for a process, not a subsystem.
Info log level
Info level log statements serve the following specific purposes.
- Major action is taken, such as initializing an archive object, or deleting a file from an archive
- Noting each public method has been called, and the arguments with which it was called
- Signposting the major actions a public method takes
- Notifying that an atypical condition has occurred (such as an action causing an early stop in a block or a NO return value)
- Noting that a loop is about to occur, which will contain debug-level messages for each iteration
Debug log level
Most messages fall into this category, making it extremely verbose. All non-error messages that don't fall into either of the other two categories should be debug-level, with some examples of specific cases below.
- Any log message in a private method
- Noting variable and argument values in a method
- Indicating that everything is working as expected
- Indicating what happens during each iteration of a loop (or documenting that an iteration has happened at all)
Error log level
- Every
NSErrorgenerated should get logged with the same detail message as theNSErrorobject itself NSErrorlog messages should contain the string of the error code's enumeration value (e.g."URKErrorCodeArchiveNotFound") when it is known at design time- Errors should reported everywhere they're encountered, making it easier to trace their flows through the call stack
- Early exits that result in desired work not being performed
Fault log level
Used when a Cocoa framework method comes back with an error. There are only a handful of uses
Activities
- Public methods have an English activity names with spaces, and are title-case
- Private methods each have an activity with the method's name
- Sub-activities are created for significant scope changes, such as when inside an action block, but not if no significant work is done before entering that action
- Top-level activities within a method have variables named
activity, with more specific labels given to sub-activities - If a method is strictly an overload that calls out to another overload without doing anything else, it should not define its own activity
Running the tests
Open UnrarKit.xcworkspace and select the UnrarKit scheme with My Mac, an iOS simulator, or an Apple Vision Pro simulator as the destination. The default Complete plan runs every XCTest available on that platform. Fast skips the macOS tests that generate large archives or stress file descriptors. Rigorous runs the complete selection under Address Sanitizer, Thread and Undefined Behavior Sanitizers together, and Guard Malloc.
For example, this runs Guard Malloc locally.
xcodebuild test -workspace UnrarKit.xcworkspace -scheme UnrarKit \
-destination 'platform=macOS' -testPlan Rigorous -only-test-configuration 'Guard Malloc'
CircleCI runs Complete and all three Rigorous configurations on macOS and the iOS simulator. Each has its own XCTest class discovery and JUnit report so failed classes can be rerun. On macOS, CircleCI also starts a fresh Thread Sanitizer process for the concurrent extraction test to exercise UnRAR’s first-use initialization. The Guard Malloc configuration explicitly loads libgmalloc into the XCTest process for command-line runs.
On the Apple Vision Pro simulator, CircleCI runs the Complete plan and verifies that a SwiftPM consumer can list and extract an archive. To run those checks locally on a specific simulator, set VISIONOS_TEST_DESTINATION to platform=visionOS Simulator,id=<UDID>.
Publishing a release
Release from the green commit on the version branch. Write the release-specific notes as Markdown in a file outside the checkout, then run the following commands (substitute the intended tag and notes file).
git fetch origin v2.11
git switch --detach origin/v2.11
tag=2.11.0-beta2
python3 Scripts/release.py tag "$tag" /tmp/unrarkit-release-notes.md
python3 Scripts/release.py notes "$tag"
git push --no-follow-tags origin "refs/tags/$tag"
The helper creates one local annotated tag on HEAD. Its final UnrarKit-Build trailer records one plus the number of release tags already on origin for the same numeric marketing version. For example, 2.0-beta, 2.0-beta2, 2.0-beta3, and 2.0.0-beta4 all count toward 2.0.0. Historical RC tags count too. Create and push one release at a time so the next tag sees the previous one on origin. Use a distinct commit for each release so SwiftPM can identify the tag unambiguously.
Branch pushes keep the normal CircleCI test and package validation jobs. A release tag runs the platform tests and validates Carthage and SwiftPM with Xcode 27.2. The GitHub job then publishes the tested XCFramework ZIP with the tag's notes. Beta tags produce prereleases. The job uses the unrarkit-release CircleCI context with a project-restricted GH_TOKEN that has Contents write access.
Building a release locally. With the tagged commit checked out, run URK_RELEASE_TAG="$tag" ./Scripts/archive-carthage.sh. For a direct Xcode build, run python3 Scripts/release.py xcconfig "$tag" > /tmp/UnrarKit-version.xcconfig and pass -xcconfig /tmp/UnrarKit-version.xcconfig to xcodebuild. The tag object is sufficient even in a shallow clone. The built framework and resource bundle report the full tag in AbbeyCodeReleaseVersion, the normalized marketing version in CFBundleShortVersionString, and the recorded build in CFBundleVersion. A Carthage source build reads its release tag from the consumer’s Cartfile.resolved and the build number from the annotated tag in Carthage’s local Git cache (or the dependency’s Git checkout with --use-submodules). Revision-pinned Carthage builds and ordinary Xcode builds without release settings use development, 0.0.0, and 0.
SwiftPM. The from-source library exports the full tag in UnrarKitVersionString and the build number in UnrarKitVersionNumber. SwiftPM supplies the tag name through its manifest context. The manifest reads the build trailer from the checkout or the local SwiftPM Git cache. If only the tag name is available, the string retains the tag and the number is zero. Without a unique release tag on the commit (including a vendored copy without its own Git metadata), the symbols report development and zero. SwiftPM generates its own resource bundle Info.plist. Earlier releases retain the metadata shipped at their original commits.
Credits
- Dov Frankel ([email protected])
- Rogerio Pereira Araujo ([email protected])
- Vicent Scott ([email protected])
Explorar proyectos relacionados
Cargando…