Browse Source

Add option to not create resume data on cancel for DownloadRequest (#2851)

ullstrm 6 years ago
parent
commit
a54d935b26
2 changed files with 47 additions and 2 deletions
  1. 13 2
      Source/Request.swift
  2. 34 0
      Tests/DownloadTests.swift

+ 13 - 2
Source/Request.swift

@@ -497,8 +497,19 @@ open class DownloadRequest: Request {
     // MARK: State
 
     /// Cancels the request.
-    open override func cancel() {
-        downloadDelegate.downloadTask.cancel { self.downloadDelegate.resumeData = $0 }
+    override open func cancel() {
+        cancel(createResumeData: true)
+    }
+    
+    /// Cancels the request.
+    ///
+    /// - parameter createResumeData: Determines whether resume data is created via the underlying download task or not.
+    open func cancel(createResumeData: Bool) {
+        if createResumeData {
+            downloadDelegate.downloadTask.cancel { self.downloadDelegate.resumeData = $0 }
+        } else {
+            downloadDelegate.downloadTask.cancel()
+        }
 
         NotificationCenter.default.post(
             name: Notification.Name.Task.DidCancel,

+ 34 - 0
Tests/DownloadTests.swift

@@ -515,6 +515,40 @@ class DownloadResumeDataTestCase: BaseTestCase {
 
         progressValues.forEach { XCTAssertGreaterThanOrEqual($0, 0.4) }
     }
+    
+    func testThatDownloadCanBeCancelledWithoutResumeData() {
+        // Given
+        let expectation = self.expectation(description: "Download should be cancelled")
+        var cancelled = false
+        
+        var response: DefaultDownloadResponse?
+        
+        // When
+        let download = Alamofire.download(urlString)
+        download.downloadProgress { progress in
+            guard !cancelled else { return }
+            
+            if progress.fractionCompleted > 0.1 {
+                download.cancel(createResumeData: false)
+                cancelled = true
+            }
+        }
+        download.response { resp in
+            response = resp
+            expectation.fulfill()
+        }
+        
+        waitForExpectations(timeout: timeout, handler: nil)
+        
+        // Then
+        XCTAssertNotNil(response?.request)
+        XCTAssertNotNil(response?.response)
+        XCTAssertNil(response?.destinationURL)
+        XCTAssertNotNil(response?.error)
+        
+        XCTAssertNil(response?.resumeData)
+        XCTAssertNil(download.resumeData)
+    }
 }
 
 // MARK: -