Browse Source

Remove some generics, cleanup whitespace.

Jon Shier 7 years ago
parent
commit
10941f0568

+ 7 - 7
Source/Alamofire.swift

@@ -129,11 +129,11 @@ extension URLRequest {
 ///
 /// - returns: The created `DataRequest`.
 @discardableResult
-public func request<Convertible: URLConvertible>(_ url: Convertible,
-                                                 method: HTTPMethod = .get,
-                                                 parameters: Parameters? = nil,
-                                                 encoding: ParameterEncoding = URLEncoding.default,
-                                                 headers: HTTPHeaders? = nil) -> DataRequest {
+public func request(_ url: URLConvertible,
+                    method: HTTPMethod = .get,
+                    parameters: Parameters? = nil,
+                    encoding: ParameterEncoding = URLEncoding.default,
+                    headers: HTTPHeaders? = nil) -> DataRequest {
     return SessionManager.default.request(url,
                                           method: method,
                                           parameters: parameters,
@@ -171,8 +171,8 @@ public func request<Convertible: URLRequestConvertible>(_ urlRequest: Convertibl
 ///
 /// - returns: The created `DownloadRequest`.
 @discardableResult
-public func download<Convertible: URLConvertible>(
-    _ url: Convertible,
+public func download(
+    _ url: URLConvertible,
     method: HTTPMethod = .get,
     parameters: Parameters? = nil,
     encoding: ParameterEncoding = URLEncoding.default,

+ 41 - 41
Source/Request.swift

@@ -36,7 +36,7 @@ protocol RequestDelegate: AnyObject {
 open class Request {
     /// A closure executed when monitoring upload or download progress of a request.
     public typealias ProgressHandler = (Progress) -> Void
-    
+
     // TODO: Make publicly readable properties protected?
     public enum State {
         case initialized, resumed, suspended, cancelled
@@ -64,7 +64,7 @@ open class Request {
     open let internalQueue: OperationQueue
 
     // MARK: - Updated State
-    
+
     let uploadProgress = Progress()
     let downloadProgress = Progress()
     var uploadProgressHandler: (handler: ProgressHandler, queue: DispatchQueue)?
@@ -99,7 +99,7 @@ open class Request {
     public var initialTask: URLSessionTask? { return tasks.first }
     public var finalTask: URLSessionTask? { return tasks.last }
     public var task: URLSessionTask? { return finalTask }
-    
+
     fileprivate(set) public var error: Error?
     private(set) var credential: URLCredential?
     fileprivate(set) var validators: [() -> Void] = []
@@ -158,18 +158,18 @@ open class Request {
 
         eventMonitor?.request(self, didCreateTask: task)
     }
-    
+
     func updateUploadProgress(totalBytesSent: Int64, totalBytesExpectedToSend: Int64) {
         uploadProgress.totalUnitCount = totalBytesExpectedToSend
         uploadProgress.completedUnitCount = totalBytesSent
-        
+
         uploadProgressHandler?.queue.async { self.uploadProgressHandler?.handler(self.uploadProgress) }
     }
-    
+
     // Resets task related state
     func reset() {
         error = nil
-        
+
         uploadProgress.totalUnitCount = 0
         uploadProgress.completedUnitCount = 0
         downloadProgress.totalUnitCount = 0
@@ -288,7 +288,7 @@ open class Request {
 
         return self
     }
-    
+
     /// Sets a closure to be called periodically during the lifecycle of the `Request` as data is read from the server.
     ///
     /// - parameter queue:   The dispatch queue to execute the closure on.
@@ -298,12 +298,12 @@ open class Request {
     @discardableResult
     open func downloadProgress(queue: DispatchQueue = DispatchQueue.main, closure: @escaping ProgressHandler) -> Self {
         underlyingQueue.async { self.downloadProgressHandler = (closure, queue) }
-        
+
         return self
     }
-    
+
     // MARK: Upload Progress
-    
+
     /// Sets a closure to be called periodically during the lifecycle of the `UploadRequest` as data is sent to
     /// the server.
     ///
@@ -317,7 +317,7 @@ open class Request {
     @discardableResult
     open func uploadProgress(queue: DispatchQueue = DispatchQueue.main, closure: @escaping ProgressHandler) -> Self {
         underlyingQueue.async { self.uploadProgressHandler = (closure, queue) }
-        
+
         return self
     }
 }
@@ -336,9 +336,9 @@ extension Request: Hashable {
 
 open class DataRequest: Request {
     let convertible: URLRequestConvertible
-    
+
     private(set) var data: Data?
-    
+
     init(id: UUID = UUID(),
          convertible: URLRequestConvertible,
          underlyingQueue: DispatchQueue,
@@ -346,7 +346,7 @@ open class DataRequest: Request {
          eventMonitor: RequestEventMonitor?,
          delegate: RequestDelegate) {
         self.convertible = convertible
-        
+
         super.init(id: id,
                    underlyingQueue: underlyingQueue,
                    serializationQueue: serializationQueue,
@@ -356,27 +356,27 @@ open class DataRequest: Request {
 
     override func reset() {
         super.reset()
-        
+
         data = nil
     }
-    
+
     func didRecieve(data: Data) {
         if self.data == nil {
             self.data = data
         } else {
             self.data?.append(data)
         }
-        
+
         updateDownloadProgress()
     }
-    
+
     func updateDownloadProgress() {
         let totalBytesRecieved = Int64(self.data?.count ?? 0)
         let totalBytesExpected = task?.response?.expectedContentLength ?? NSURLSessionTransferSizeUnknown
-        
+
         downloadProgress.totalUnitCount = totalBytesExpected
         downloadProgress.completedUnitCount = totalBytesRecieved
-        
+
         downloadProgressHandler?.queue.async { self.downloadProgressHandler?.handler(self.downloadProgress) }
     }
 
@@ -413,10 +413,10 @@ open class DownloadRequest: Request {
     public struct Options: OptionSet {
         /// A `DownloadOptions` flag that creates intermediate directories for the destination URL if specified.
         public static let createIntermediateDirectories = Options(rawValue: 1 << 0)
-        
+
         /// A `DownloadOptions` flag that removes a previous file from the destination URL if specified.
         public static let removePreviousFile = Options(rawValue: 1 << 1)
-        
+
         /// Returns the raw bitmask value of the option and satisfies the `RawRepresentable` protocol.
         public let rawValue: Int
 
@@ -456,7 +456,7 @@ open class DownloadRequest: Request {
             return (url, options)
         }
     }
-    
+
     public enum Downloadable {
         case request(URLRequestConvertible)
         case resumeData(Data)
@@ -493,10 +493,10 @@ open class DownloadRequest: Request {
                    eventMonitor: eventMonitor,
                    delegate: delegate)
     }
-    
+
     override func reset() {
         super.reset()
-        
+
         temporaryURL = nil
         destinationURL = nil
         resumeData = nil
@@ -504,9 +504,9 @@ open class DownloadRequest: Request {
 
     func didComplete(task: URLSessionTask, with url: URL) {
         temporaryURL = url
-        
+
         guard let destination = destination, let response = response else { return }
-        
+
         let (destinationURL, options) = destination(url, response)
         self.destinationURL = destinationURL
         // TODO: Inject FileManager?
@@ -514,45 +514,45 @@ open class DownloadRequest: Request {
             if options.contains(.removePreviousFile), FileManager.default.fileExists(atPath: destinationURL.path) {
                 try FileManager.default.removeItem(at: destinationURL)
             }
-            
+
             if options.contains(.createIntermediateDirectories) {
                 let directory = destinationURL.deletingLastPathComponent()
                 try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
             }
-            
+
             try FileManager.default.moveItem(at: url, to: destinationURL)
         } catch {
             self.error = error
         }
     }
-    
+
     func updateDownloadProgress(bytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
         downloadProgress.totalUnitCount = totalBytesExpectedToWrite
         downloadProgress.completedUnitCount += bytesWritten
-        
+
         downloadProgressHandler?.queue.async { self.downloadProgressHandler?.handler(self.downloadProgress) }
     }
-    
+
     override func task(for request: URLRequest, using session: URLSession) -> URLSessionTask {
         return session.downloadTask(with: request)
     }
-    
+
     open func task(forResumeData data: Data, using session: URLSession) -> URLSessionTask {
         return session.downloadTask(withResumeData: data)
     }
-    
+
     @discardableResult
     public override func cancel() -> Self {
         // TODO: EventMonitor?
         guard state.canTransitionTo(.cancelled) else { return self }
-        
+
         state = .cancelled
-        
+
         delegate?.cancelDownloadRequest(self) { self.resumeData = $0 }
-        
+
         return self
     }
-    
+
     /// Validates the request, using the specified closure.
     ///
     /// If validation fails, subsequent calls to response handlers will have an associated error.
@@ -613,14 +613,14 @@ open class UploadRequest: DataRequest {
                    serializationQueue: serializationQueue,
                    eventMonitor: eventMonitor,
                    delegate: delegate)
-        
+
         // Automatically remove temporary upload files (e.g. multipart form data)
         internalQueue.addOperation {
             guard
                 let uploadable = self.uploadable,
                 case let .file(url, shouldRemove) = uploadable,
                 shouldRemove else { return }
-            
+
             // TODO: Abstract file manager
             try? FileManager.default.removeItem(at: url)
         }

+ 12 - 12
Source/Response.swift

@@ -159,35 +159,35 @@ extension DataResponse {
 public struct DownloadResponse<Value> {
     /// The URL request sent to the server.
     public let request: URLRequest?
-    
+
     /// The server's response to the URL request.
     public let response: HTTPURLResponse?
-    
+
     /// The temporary destination URL of the data returned from the server.
     public let temporaryURL: URL?
-    
+
     /// The final destination URL of the data returned from the server if it was moved.
     public let destinationURL: URL?
-    
+
     /// The resume data generated if the request was cancelled.
     public let resumeData: Data?
-    
+
     /// The result of response serialization.
     public let result: Result<Value>
-    
+
     /// The timeline of the complete lifecycle of the request.
 //    public let timeline: Timeline
-    
+
     public let metrics: URLSessionTaskMetrics?
-    
+
     /// Returns the associated value of the result if it is a success, `nil` otherwise.
     public var value: Value? { return result.value }
-    
+
     /// Returns the associated error value if the result if it is a failure, `nil` otherwise.
     public var error: Error? { return result.error }
-    
+
 //    var _metrics: AnyObject?
-    
+
     /// Creates a `DownloadResponse` instance with the specified parameters derived from response serialization.
     ///
     /// - parameter request:        The URL request sent to the server.
@@ -215,7 +215,7 @@ public struct DownloadResponse<Value> {
         self.resumeData = resumeData
         self.metrics = metrics
         self.result = result
-        
+
 //        self.timeline = timeline
     }
 }

+ 5 - 5
Source/ResponseSerialization.swift

@@ -30,7 +30,7 @@ import Foundation
 public protocol DataResponseSerializerProtocol {
     /// The type of serialized object to be created by this serializer.
     associatedtype SerializedObject
-    
+
 //    /// The HTTP response codes used to indicate empty responses. Defaults to `[204, 205]`.
 //    var emptyDataResponseCodes: Set<Int> { get }
 //
@@ -50,7 +50,7 @@ public protocol DataResponseSerializerProtocol {
 public protocol DownloadResponseSerializerProtocol {
     /// The type of serialized object to be created by this `DownloadResponseSerializerType`.
     associatedtype SerializedObject
-    
+
 //    /// The HTTP response codes used to indicate empty responses. Defaults to `[204, 205]`.
 //    var emptyResponseCodes: Set<Int> { get }
 //
@@ -259,10 +259,10 @@ extension DownloadRequest {
                                             resumeData: self.resumeData,
                                             metrics: self.metrics,
                                             result: result)
-            
+
             (queue ?? .main).async { completionHandler(response) }
         }
-        
+
         return self
     }
 
@@ -295,7 +295,7 @@ extension DownloadRequest {
                                             resumeData: self.resumeData,
                                             metrics: self.metrics,
                                             result: result)
-            
+
             (queue ?? .main).async { completionHandler(response) }
         }
 

+ 13 - 13
Source/SessionDelegate.swift

@@ -55,25 +55,25 @@ open class SessionDelegate: NSObject {
 
         resumeOrSuspendTask(task, ifNecessaryForRequest: request)
     }
-    
+
     func didReceiveResumeData(_ data: Data, for request: DownloadRequest) {
         guard let manager = manager else { fatalError("Received didReceiveResumeData but there is no manager.") }
-        
+
         guard !request.isCancelled else { return }
-        
+
         let task = request.task(forResumeData: data, using: manager.session)
         requestTaskMap[request] = task
         request.didCreateTask(task)
-        
+
         resumeOrSuspendTask(task, ifNecessaryForRequest: request)
     }
-    
+
     func resumeOrSuspendTask(_ task: URLSessionTask, ifNecessaryForRequest request: Request) {
         if startRequestsImmediately || request.isResumed {
             task.resume()
             request.didResume()
         }
-        
+
         if request.isSuspended {
             task.suspend()
             request.didSuspend()
@@ -118,7 +118,7 @@ extension SessionDelegate: RequestDelegate {
             task.cancel()
         }
     }
-    
+
     func cancelDownloadRequest(_ request: DownloadRequest, byProducingResumeData: @escaping (Data?) -> Void) {
         queue?.async {
             guard let downloadTask = self.requestTaskMap[request] as? URLSessionDownloadTask else {
@@ -126,7 +126,7 @@ extension SessionDelegate: RequestDelegate {
                 request.finish()
                 return
             }
-            
+
             downloadTask.cancel { (data) in
                 self.queue?.async {
                     byProducingResumeData(data)
@@ -228,7 +228,7 @@ extension SessionDelegate: URLSessionTaskDelegate {
                                  didSendBodyData: bytesSent,
                                  totalBytesSent: totalBytesSent,
                                  totalBytesExpectedToSend: totalBytesExpectedToSend)
-        
+
         requestTaskMap[task]?.updateUploadProgress(totalBytesSent: totalBytesSent,
                                                    totalBytesExpectedToSend: totalBytesExpectedToSend)
 
@@ -360,11 +360,11 @@ extension SessionDelegate: URLSessionDownloadDelegate {
                                  downloadTask: downloadTask,
                                  didResumeAtOffset: fileOffset,
                                  expectedTotalBytes: expectedTotalBytes)
-        
+
         guard let downloadRequest = requestTaskMap[downloadTask] as? DownloadRequest else {
             fatalError("No DownloadRequest found for downloadTask: \(downloadTask)")
         }
-        
+
         downloadRequest.updateDownloadProgress(bytesWritten: fileOffset,
                                                totalBytesExpectedToWrite: expectedTotalBytes)
     }
@@ -376,11 +376,11 @@ extension SessionDelegate: URLSessionDownloadDelegate {
                                  didWriteData: bytesWritten,
                                  totalBytesWritten: totalBytesWritten,
                                  totalBytesExpectedToWrite: totalBytesExpectedToWrite)
-        
+
         guard let downloadRequest = requestTaskMap[downloadTask] as? DownloadRequest else {
             fatalError("No DownloadRequest found for downloadTask: \(downloadTask)")
         }
-        
+
         downloadRequest.updateDownloadProgress(bytesWritten: bytesWritten,
                                                totalBytesExpectedToWrite: totalBytesExpectedToWrite)
     }

+ 9 - 9
Source/SessionManager.swift

@@ -132,7 +132,7 @@ open class SessionManager {
 
         return request
     }
-    
+
     open func download(resumingWith data: Data,
                        to destination: DownloadRequest.Destination? = nil) -> DownloadRequest {
         let request = DownloadRequest(downloadable: .resumeData(data),
@@ -140,9 +140,9 @@ open class SessionManager {
                                       eventMonitor: eventMonitor,
                                       delegate: delegate,
                                       destination: destination)
-        
+
         perform(request)
-        
+
         return request
     }
 
@@ -251,13 +251,13 @@ open class SessionManager {
 
         return request
     }
-    
+
     // MARK: Downloadable
-    
+
 //    func download
 
     // MARK: Perform
-    
+
     func perform(_ request: Request) {
         switch request {
         case let r as DataRequest: perform(r)
@@ -300,14 +300,14 @@ open class SessionManager {
             }
         }
     }
-    
+
     func performSetupOperations(for request: Request, convertible: URLRequestConvertible) {
         do {
             let initialRequest = try convertible.asURLRequest()
             self.rootQueue.async { request.didCreateURLRequest(initialRequest) }
-            
+
             guard !request.isCancelled else { return }
-            
+
             if let adapter = adapter {
                 do {
                     let adaptedRequest = try adapter.adapt(initialRequest)

+ 3 - 3
Tests/DownloadTests.swift

@@ -31,12 +31,12 @@ class DownloadInitializationTestCase: BaseTestCase {
         // Given
         let urlString = "https://httpbin.org/get"
         let expectation = self.expectation(description: "download should complete")
-        
+
         // When
         let request = Alamofire.download(urlString).response { (resp) in
             expectation.fulfill()
         }
-        
+
         waitForExpectations(timeout: timeout, handler: nil)
 
         // Then
@@ -56,7 +56,7 @@ class DownloadInitializationTestCase: BaseTestCase {
         let request = Alamofire.download(urlString, headers: headers).response { (resp) in
             expectation.fulfill()
         }
-        
+
         waitForExpectations(timeout: timeout, handler: nil)
 
         // Then

+ 13 - 13
Tests/UploadTests.swift

@@ -37,7 +37,7 @@ class UploadFileInitializationTestCase: BaseTestCase {
         let request = Alamofire.upload(imageURL, to: urlString).response { _ in
             expectation.fulfill()
         }
-        
+
         waitForExpectations(timeout: timeout, handler: nil)
 
         // Then
@@ -58,7 +58,7 @@ class UploadFileInitializationTestCase: BaseTestCase {
         let request = Alamofire.upload(imageURL, to: urlString, method: .post, headers: headers).response { _ in
             expectation.fulfill()
         }
-        
+
         waitForExpectations(timeout: timeout, handler: nil)
 
         // Then
@@ -85,7 +85,7 @@ class UploadDataInitializationTestCase: BaseTestCase {
         let request = Alamofire.upload(Data(), to: urlString).response { _ in
             expectation.fulfill()
         }
-        
+
         waitForExpectations(timeout: timeout, handler: nil)
 
         // Then
@@ -105,7 +105,7 @@ class UploadDataInitializationTestCase: BaseTestCase {
         let request = Alamofire.upload(Data(), to: urlString, headers: headers).response { _ in
             expectation.fulfill()
         }
-        
+
         waitForExpectations(timeout: timeout, handler: nil)
 
         // Then
@@ -115,7 +115,7 @@ class UploadDataInitializationTestCase: BaseTestCase {
 
         let authorizationHeader = request.request?.value(forHTTPHeaderField: "Authorization") ?? ""
         XCTAssertEqual(authorizationHeader, "123456", "Authorization header is incorrect")
-        
+
         XCTAssertNotNil(request.response, "response should not be nil")
     }
 }
@@ -134,7 +134,7 @@ class UploadStreamInitializationTestCase: BaseTestCase {
         let request = Alamofire.upload(imageStream, to: urlString).response { _ in
             expectation.fulfill()
         }
-        
+
         waitForExpectations(timeout: timeout, handler: nil)
 
         // Then
@@ -156,7 +156,7 @@ class UploadStreamInitializationTestCase: BaseTestCase {
         let request = Alamofire.upload(imageStream, to: urlString, headers: headers).response { _ in
             expectation.fulfill()
         }
-        
+
         waitForExpectations(timeout: timeout, handler: nil)
 
         // Then
@@ -311,7 +311,7 @@ class UploadMultipartFormDataTestCase: BaseTestCase {
         let urlString = "https://httpbin.org/post"
         let frenchData = Data("français".utf8)
         let japaneseData = Data("日本語".utf8)
-        
+
         let expectation = self.expectation(description: "multipart form data upload should succeed")
         var response: DataResponse<Data?>?
 
@@ -352,7 +352,7 @@ class UploadMultipartFormDataTestCase: BaseTestCase {
 
         let expectation = self.expectation(description: "multipart form data upload should succeed")
         var response: DataResponse<Data?>?
-        
+
         // When
         let request = Alamofire.upload(
                         multipartFormData: { multipartFormData in
@@ -372,7 +372,7 @@ class UploadMultipartFormDataTestCase: BaseTestCase {
             XCTFail("Uploadable is not .data")
             return
         }
-        
+
         XCTAssertTrue(response?.result.isSuccess ==  true)
     }
 
@@ -445,7 +445,7 @@ class UploadMultipartFormDataTestCase: BaseTestCase {
             XCTFail("Uploadable is not .file")
             return
         }
-        
+
         XCTAssertTrue(response?.result.isSuccess == true)
         XCTAssertFalse(FileManager.default.fileExists(atPath: url.path))
     }
@@ -478,7 +478,7 @@ class UploadMultipartFormDataTestCase: BaseTestCase {
             XCTFail("Uploadable is not .file")
             return
         }
-        
+
         XCTAssertTrue(response?.result.isSuccess == true)
 
         if
@@ -525,7 +525,7 @@ class UploadMultipartFormDataTestCase: BaseTestCase {
                 response = defaultResponse.response
                 data = defaultResponse.data
                 error = defaultResponse.error
-                
+
                 expectation.fulfill()
             }