@@ -17,13 +17,16 @@ public enum ZipError: Error {
1717 case unzipFail
1818 /// Zip fail
1919 case zipFail
20-
20+ /// Operation Cancelled
21+ case operationCancelled
22+
2123 /// User readable description
2224 public var description : String {
2325 switch self {
2426 case . fileNotFound: return NSLocalizedString ( " File not found. " , comment: " " )
2527 case . unzipFail: return NSLocalizedString ( " Failed to unzip file. " , comment: " " )
2628 case . zipFail: return NSLocalizedString ( " Failed to zip file. " , comment: " " )
29+ case . operationCancelled: return NSLocalizedString ( " Operation cancelled " , comment: " " )
2730 }
2831 }
2932}
@@ -50,12 +53,16 @@ public enum ZipCompression: Int {
5053
5154/// Zip class
5255public class Zip {
53-
5456 /**
5557 Set of vaild file extensions
5658 */
5759 internal static var customFileExtensions : Set < String > = [ ]
5860
61+ /**
62+ Cancellation block. This is set once the progress tracker is has been created
63+ */
64+ public static var cancelCurrentOperation : ( ( ) -> Void ) = { }
65+
5966 // MARK: Lifecycle
6067
6168 /**
@@ -113,6 +120,8 @@ public class Zip {
113120 progressTracker. isPausable = false
114121 progressTracker. kind = ProgressKind . file
115122
123+ cancelCurrentOperation = { progressTracker. cancel ( ) }
124+
116125 // Begin unzipping
117126 let zip = unzOpen64 ( path)
118127 defer {
@@ -234,16 +243,19 @@ public class Zip {
234243 }
235244
236245 progressTracker. completedUnitCount = Int64 ( currentPosition)
237-
238- } while ( ret == UNZ_OK && ret != UNZ_END_OF_LIST_OF_FILE)
246+
247+ } while ( ret == UNZ_OK && ret != UNZ_END_OF_LIST_OF_FILE) && !progressTracker. isCancelled
248+
249+ guard !progressTracker. isCancelled else {
250+ throw ZipError . operationCancelled
251+ }
239252
240253 // Completed. Update progress handler.
241254 if let progressHandler = progress{
242255 progressHandler ( 1.0 )
243256 }
244257
245258 progressTracker. completedUnitCount = Int64 ( totalSize)
246-
247259 }
248260
249261 // MARK: Zip
@@ -297,6 +309,8 @@ public class Zip {
297309 progressTracker. isPausable = false
298310 progressTracker. kind = ProgressKind . file
299311
312+ cancelCurrentOperation = { progressTracker. cancel ( ) }
313+
300314 // Begin Zipping
301315 let zip = zipOpen ( destinationPath, APPEND_STATUS_CREATE)
302316 for path in processedPaths {
@@ -338,6 +352,10 @@ public class Zip {
338352 }
339353 var length : Int = 0
340354 while ( feof ( input) == 0 ) {
355+ guard !progressTracker. isCancelled else {
356+ throw ZipError . operationCancelled
357+ }
358+
341359 length = fread ( buffer, 1 , chunkSize, input)
342360 zipWriteInFileInZip ( zip, buffer, UInt32 ( length) )
343361 }
0 commit comments