@@ -97,13 +97,10 @@ public struct NKCommon: Sendable {
9797 completion: @escaping ( _ filesChunk: [ ( fileName: String , size: Int64 ) ] , _ error: Error ? ) -> Void = { _, _ in } ) {
9898 // Return existing chunks immediately
9999 if !filesChunk. isEmpty {
100+ numChunks ( max ( 0 , filesChunk. count - 1 ) )
100101 return completion ( filesChunk, nil )
101102 }
102103
103- defer {
104- NotificationCenter . default. removeObserver ( self , name: notificationCenterChunkedFileStop, object: nil )
105- }
106-
107104 let fileManager = FileManager . default
108105 var isDirectory : ObjCBool = false
109106 var reader : FileHandle ?
@@ -116,10 +113,6 @@ public struct NKCommon: Sendable {
116113 let bufferSize = 1_000_000
117114 var stop = false
118115
119- NotificationCenter . default. addObserver ( forName: notificationCenterChunkedFileStop, object: nil , queue: nil ) { _ in
120- stop = true
121- }
122-
123116 // If max chunk count is > 10000 (max count), add + 100 MB to the chunk size to reduce the count. This is an edge case.
124117 let inputFilePath = inputDirectory + " / " + fileName
125118 let totalSize = getFileSize ( filePath: inputFilePath)
@@ -147,6 +140,17 @@ public struct NKCommon: Sendable {
147140 return completion ( [ ] , NSError ( domain: " chunkedFile " , code: - 1 , userInfo: [ NSLocalizedDescriptionKey: " Failed to open the input file for reading. " ] ) )
148141 }
149142
143+ let tokenObserver = NotificationCenter . default. addObserver ( forName: notificationCenterChunkedFileStop, object: nil , queue: nil ) { _ in
144+ stop = true
145+ }
146+
147+ defer {
148+ NotificationCenter . default. removeObserver ( tokenObserver)
149+
150+ try ? writer? . close ( )
151+ try ? reader? . close ( )
152+ }
153+
150154 outerLoop: repeat {
151155 if stop {
152156 return completion ( [ ] , NSError ( domain: " chunkedFile " , code: - 5 , userInfo: [ NSLocalizedDescriptionKey: " Chunking was stopped by user request or system notification. " ] ) )
@@ -228,9 +232,6 @@ public struct NKCommon: Sendable {
228232 }
229233 } while true
230234
231- writer? . closeFile ( )
232- reader? . closeFile ( )
233-
234235 // Update incremental chunk sizes
235236 for i in 0 ..< filesChunk. count {
236237 let path = outputDirectory + " / " + filesChunk[ i] . fileName
0 commit comments