From c64fc5f34d34b4c7f2348c0c9318c68babd784b0 Mon Sep 17 00:00:00 2001 From: Syo Ikeda Date: Mon, 8 Aug 2016 13:42:30 +0900 Subject: [PATCH 01/38] Update dependencies --- .gitmodules | 2 +- Cartfile | 2 +- Cartfile.private | 2 +- Cartfile.resolved | 4 ++-- Carthage/Checkouts/OHHTTPStubs | 2 +- Carthage/Checkouts/Result | 2 +- 6 files changed, 7 insertions(+), 7 deletions(-) diff --git a/.gitmodules b/.gitmodules index fc535505..30480090 100644 --- a/.gitmodules +++ b/.gitmodules @@ -3,4 +3,4 @@ url = https://github.com/antitypical/Result.git [submodule "Carthage/Checkouts/OHHTTPStubs"] path = Carthage/Checkouts/OHHTTPStubs - url = https://github.com/ikesyo/OHHTTPStubs.git + url = https://github.com/AliSoftware/OHHTTPStubs.git diff --git a/Cartfile b/Cartfile index e1971052..4868aaec 100644 --- a/Cartfile +++ b/Cartfile @@ -1 +1 @@ -github "antitypical/Result" ~> 2.1.2 +github "antitypical/Result" "3.0.0-alpha.2" diff --git a/Cartfile.private b/Cartfile.private index db0e286d..7f203a08 100644 --- a/Cartfile.private +++ b/Cartfile.private @@ -1 +1 @@ -github "ikesyo/OHHTTPStubs" "swift2.3" +github "AliSoftware/OHHTTPStubs" "4995ecd" diff --git a/Cartfile.resolved b/Cartfile.resolved index 3e7580e6..19067c74 100644 --- a/Cartfile.resolved +++ b/Cartfile.resolved @@ -1,2 +1,2 @@ -github "ikesyo/OHHTTPStubs" "b9abbd044ebeecbedf8db10721ed24e4bfe07f29" -github "antitypical/Result" "2.1.2" +github "AliSoftware/OHHTTPStubs" "4995ecd762abdd81227d14faf65fde003fbbe789" +github "antitypical/Result" "3.0.0-alpha.2" diff --git a/Carthage/Checkouts/OHHTTPStubs b/Carthage/Checkouts/OHHTTPStubs index b9abbd04..4995ecd7 160000 --- a/Carthage/Checkouts/OHHTTPStubs +++ b/Carthage/Checkouts/OHHTTPStubs @@ -1 +1 @@ -Subproject commit b9abbd044ebeecbedf8db10721ed24e4bfe07f29 +Subproject commit 4995ecd762abdd81227d14faf65fde003fbbe789 diff --git a/Carthage/Checkouts/Result b/Carthage/Checkouts/Result index efa4c04a..03eb2c27 160000 --- a/Carthage/Checkouts/Result +++ b/Carthage/Checkouts/Result @@ -1 +1 @@ -Subproject commit efa4c04a65ba0af37ca5320993875f73ecb1cfa0 +Subproject commit 03eb2c274eb3cab2b2bd4b25586b3d6325607e2c From 21e4379dd0d6dd079956097f6d0d5996c3354f48 Mon Sep 17 00:00:00 2001 From: Syo Ikeda Date: Mon, 8 Aug 2016 19:14:47 +0900 Subject: [PATCH 02/38] Initial Swift 3 migration --- APIKit.xcodeproj/project.pbxproj | 12 +- .../BodyParametersType.swift | 8 +- .../FormURLEncodedBodyParameters.swift | 4 +- .../JSONBodyParameters.swift | 10 +- .../MultipartFormDataBodyParameters.swift | 123 +++++++++--------- .../NSData+NSInputStream.swift | 26 ++-- Sources/CallbackQueue.swift | 10 +- Sources/DataParserType/DataParserType.swift | 2 +- .../FormURLEncodedDataParser.swift | 16 +-- Sources/DataParserType/JSONDataParser.swift | 12 +- Sources/DataParserType/StringDataParser.swift | 16 +-- Sources/Error/RequestError.swift | 10 +- Sources/Error/ResponseError.swift | 10 +- Sources/Error/SessionTaskError.swift | 14 +- Sources/RequestType.swift | 75 +++++------ .../URLEncodedSerialization.swift | 44 +++---- Sources/Session.swift | 36 ++--- .../NSURLSessionAdapter.swift | 75 ----------- .../SessionAdapterType.swift | 6 +- .../URLSessionAdapter.swift | 75 +++++++++++ Tests/APIKit/TestComponents/TestRequest.swift | 2 +- 21 files changed, 290 insertions(+), 296 deletions(-) delete mode 100644 Sources/SessionAdapterType/NSURLSessionAdapter.swift create mode 100644 Sources/SessionAdapterType/URLSessionAdapter.swift diff --git a/APIKit.xcodeproj/project.pbxproj b/APIKit.xcodeproj/project.pbxproj index fb3cae4f..094c7c4c 100644 --- a/APIKit.xcodeproj/project.pbxproj +++ b/APIKit.xcodeproj/project.pbxproj @@ -31,7 +31,7 @@ 7F85FB831C9CF25D00CEE132 /* JSONDataParserTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7F85FB821C9CF25D00CEE132 /* JSONDataParserTests.swift */; }; 7F85FB871C9CF47300CEE132 /* FormURLEncodedDataParser.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7F85FB861C9CF47300CEE132 /* FormURLEncodedDataParser.swift */; }; 7F85FB891C9CF7B000CEE132 /* FormURLEncodedDataParserTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7F85FB881C9CF7B000CEE132 /* FormURLEncodedDataParserTests.swift */; }; - 7F85FB8E1C9D317300CEE132 /* NSURLSessionAdapter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7F85FB8C1C9D317300CEE132 /* NSURLSessionAdapter.swift */; }; + 7F85FB8E1C9D317300CEE132 /* URLSessionAdapter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7F85FB8C1C9D317300CEE132 /* URLSessionAdapter.swift */; }; 7F85FB8F1C9D317300CEE132 /* SessionAdapterType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7F85FB8D1C9D317300CEE132 /* SessionAdapterType.swift */; }; 7F85FB921C9D336D00CEE132 /* NSURLSessionAdapterTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7F85FB911C9D336D00CEE132 /* NSURLSessionAdapterTests.swift */; }; 7F85FB9A1C9D3DA700CEE132 /* TestRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7F85FB981C9D3DA700CEE132 /* TestRequest.swift */; }; @@ -106,7 +106,7 @@ 7F85FB821C9CF25D00CEE132 /* JSONDataParserTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = JSONDataParserTests.swift; sourceTree = ""; }; 7F85FB861C9CF47300CEE132 /* FormURLEncodedDataParser.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FormURLEncodedDataParser.swift; sourceTree = ""; }; 7F85FB881C9CF7B000CEE132 /* FormURLEncodedDataParserTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FormURLEncodedDataParserTests.swift; sourceTree = ""; }; - 7F85FB8C1C9D317300CEE132 /* NSURLSessionAdapter.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NSURLSessionAdapter.swift; sourceTree = ""; }; + 7F85FB8C1C9D317300CEE132 /* URLSessionAdapter.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = URLSessionAdapter.swift; sourceTree = ""; }; 7F85FB8D1C9D317300CEE132 /* SessionAdapterType.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SessionAdapterType.swift; sourceTree = ""; }; 7F85FB911C9D336D00CEE132 /* NSURLSessionAdapterTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NSURLSessionAdapterTests.swift; sourceTree = ""; }; 7F85FB981C9D3DA700CEE132 /* TestRequest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TestRequest.swift; sourceTree = ""; }; @@ -279,7 +279,7 @@ isa = PBXGroup; children = ( 7F85FB8D1C9D317300CEE132 /* SessionAdapterType.swift */, - 7F85FB8C1C9D317300CEE132 /* NSURLSessionAdapter.swift */, + 7F85FB8C1C9D317300CEE132 /* URLSessionAdapter.swift */, ); path = SessionAdapterType; sourceTree = ""; @@ -464,7 +464,7 @@ 7F85FB801C9CF12600CEE132 /* JSONDataParser.swift in Sources */, 7F18BD1A1C9730ED003A31DF /* URLEncodedSerialization.swift in Sources */, 7FAC64AE1CDC7ADE00F1BB45 /* AbstractInputStream.m in Sources */, - 7F85FB8E1C9D317300CEE132 /* NSURLSessionAdapter.swift in Sources */, + 7F85FB8E1C9D317300CEE132 /* URLSessionAdapter.swift in Sources */, 7F7E8F161C8AD4B1008A13A9 /* HTTPMethod.swift in Sources */, 7FA19A421C9CBF2A005D25AE /* ResponseError.swift in Sources */, ); @@ -549,7 +549,7 @@ ENABLE_TESTABILITY = YES; GCC_NO_COMMON_BLOCKS = YES; ONLY_ACTIVE_ARCH = YES; - SWIFT_VERSION = 2.3; + SWIFT_VERSION = 3.0; }; name = Debug; }; @@ -558,7 +558,7 @@ baseConfigurationReference = 141F12111C1C96820026D415 /* Release.xcconfig */; buildSettings = { GCC_NO_COMMON_BLOCKS = YES; - SWIFT_VERSION = 2.3; + SWIFT_VERSION = 3.0; }; name = Release; }; diff --git a/Sources/BodyParametersType/BodyParametersType.swift b/Sources/BodyParametersType/BodyParametersType.swift index 6ee549bf..f6056b20 100644 --- a/Sources/BodyParametersType/BodyParametersType.swift +++ b/Sources/BodyParametersType/BodyParametersType.swift @@ -2,11 +2,11 @@ import Foundation /// `RequestBodyEntity` represents entity of HTTP body. public enum RequestBodyEntity { - /// Expresses entity as `NSData`. The associated value will be set to `NSURLRequest.HTTPBody`. - case Data(NSData) + /// Expresses entity as `Data`. The associated value will be set to `URLRequest.HTTPBody`. + case Data(Data) - /// Expresses entity as `NSInputStream`. The associated value will be set to `NSURLRequest.HTTPBodyStream`. - case InputStream(NSInputStream) + /// Expresses entity as `InputStream`. The associated value will be set to `URLRequest.HTTPBodyStream`. + case InputStream(InputStream) } /// `BodyParametersType` provides interface to parse HTTP response body and to state `Content-Type` to accept. diff --git a/Sources/BodyParametersType/FormURLEncodedBodyParameters.swift b/Sources/BodyParametersType/FormURLEncodedBodyParameters.swift index 03334b42..649e856f 100644 --- a/Sources/BodyParametersType/FormURLEncodedBodyParameters.swift +++ b/Sources/BodyParametersType/FormURLEncodedBodyParameters.swift @@ -6,10 +6,10 @@ public struct FormURLEncodedBodyParameters: BodyParametersType { public let form: [String: AnyObject] /// The string encoding of the serialized form. - public let encoding: NSStringEncoding + public let encoding: String.Encoding /// Returns `FormURLEncodedBodyParameters` that is initialized with form object and encoding. - public init(formObject: [String: AnyObject], encoding: NSStringEncoding = NSUTF8StringEncoding) { + public init(formObject: [String: AnyObject], encoding: String.Encoding = .utf8) { self.form = formObject self.encoding = encoding } diff --git a/Sources/BodyParametersType/JSONBodyParameters.swift b/Sources/BodyParametersType/JSONBodyParameters.swift index 55c33788..f793e9f9 100644 --- a/Sources/BodyParametersType/JSONBodyParameters.swift +++ b/Sources/BodyParametersType/JSONBodyParameters.swift @@ -6,10 +6,10 @@ public struct JSONBodyParameters: BodyParametersType { public let JSONObject: AnyObject /// The writing options for serialization. - public let writingOptions: NSJSONWritingOptions + public let writingOptions: JSONSerialization.WritingOptions /// Returns `JSONBodyParameters` that is initialized with JSON object and writing options. - public init(JSONObject: AnyObject, writingOptions: NSJSONWritingOptions = []) { + public init(JSONObject: AnyObject, writingOptions: JSONSerialization.WritingOptions = []) { self.JSONObject = JSONObject self.writingOptions = writingOptions } @@ -22,13 +22,13 @@ public struct JSONBodyParameters: BodyParametersType { } /// Builds `RequestBodyEntity.Data` that represents `JSONObject`. - /// - Throws: `NSError` if `NSJSONSerialization` fails to serialize `JSONObject`. + /// - Throws: `NSError` if `JSONSerialization` fails to serialize `JSONObject`. public func buildEntity() throws -> RequestBodyEntity { // If isValidJSONObject(_:) is false, dataWithJSONObject(_:options:) throws NSException. - guard NSJSONSerialization.isValidJSONObject(JSONObject) else { + guard JSONSerialization.isValidJSONObject(JSONObject) else { throw NSError(domain: NSCocoaErrorDomain, code: 3840, userInfo: nil) } - return .Data(try NSJSONSerialization.dataWithJSONObject(JSONObject, options: writingOptions)) + return .Data(try JSONSerialization.data(withJSONObject: JSONObject, options: writingOptions)) } } diff --git a/Sources/BodyParametersType/MultipartFormDataBodyParameters.swift b/Sources/BodyParametersType/MultipartFormDataBodyParameters.swift index 7e46f9cb..b13d0b54 100644 --- a/Sources/BodyParametersType/MultipartFormDataBodyParameters.swift +++ b/Sources/BodyParametersType/MultipartFormDataBodyParameters.swift @@ -8,12 +8,12 @@ import Foundation /// `FormURLEncodedBodyParameters` serializes array of `Part` for HTTP body and states its content type is multipart/form-data. public struct MultipartFormDataBodyParameters: BodyParametersType { - /// `EntityType` represents wheather the entity is expressed as `NSData` or `NSInputStream`. + /// `EntityType` represents wheather the entity is expressed as `Data` or `InputStream`. public enum EntityType { - /// Expresses the entity as `NSData`, which has faster upload speed and lager memory usage. + /// Expresses the entity as `Data`, which has faster upload speed and lager memory usage. case Data - /// Expresses the entity as `NSInputStream`, which has smaller memory usage and slower upload speed. + /// Expresses the entity as `InputStream`, which has smaller memory usage and slower upload speed. case InputStream } @@ -43,7 +43,7 @@ public struct MultipartFormDataBodyParameters: BodyParametersType { return .InputStream(inputStream) case .Data: - return .Data(try NSData(inputStream: inputStream)) + return .Data(try Data(inputStream: inputStream)) } } } @@ -51,13 +51,13 @@ public struct MultipartFormDataBodyParameters: BodyParametersType { public extension MultipartFormDataBodyParameters { /// Part represents single part of multipart/form-data. public struct Part { - public enum Error: ErrorType { + public enum Error: Swift.Error { case IllegalValue(Any) - case IllegalFileURL(NSURL) - case CannotGetFileSize(NSURL) + case IllegalFileURL(URL) + case CannotGetFileSize(URL) } - public let inputStream: NSInputStream + public let inputStream: InputStream public let name: String public let mimeType: String? public let fileName: String? @@ -66,46 +66,45 @@ public extension MultipartFormDataBodyParameters { /// Returns Part instance that has data presentation of passed value. /// `value` will be converted via `String(_:)` and serialized via `String.dataUsingEncoding(_:)`. /// If `mimeType` or `fileName` are `nil`, the fields will be omitted. - public init(value: Any, name: String, mimeType: String? = nil, fileName: String? = nil, encoding: NSStringEncoding = NSUTF8StringEncoding) throws { - guard let data = String(value).dataUsingEncoding(encoding) else { + public init(value: Any, name: String, mimeType: String? = nil, fileName: String? = nil, encoding: String.Encoding = .utf8) throws { + guard let data = String(value).data(using: encoding) else { throw Error.IllegalValue(value) } - self.inputStream = NSInputStream(data: data) + self.inputStream = InputStream(data: data) self.name = name self.mimeType = mimeType self.fileName = fileName - self.length = data.length + self.length = data.count } /// Returns Part instance that has input stream of specifed data. /// If `mimeType` or `fileName` are `nil`, the fields will be omitted. - public init(data: NSData, name: String, mimeType: String? = nil, fileName: String? = nil) { - self.inputStream = NSInputStream(data: data) + public init(data: Data, name: String, mimeType: String? = nil, fileName: String? = nil) { + self.inputStream = InputStream(data: data) self.name = name self.mimeType = mimeType self.fileName = fileName - self.length = data.length + self.length = data.count } /// Returns Part instance that has input stream of specifed file URL. /// If `mimeType` or `fileName` are `nil`, values for the fields will be detected from URL. - public init(fileURL: NSURL, name: String, mimeType: String? = nil, fileName: String? = nil) throws { - guard let inputStream = NSInputStream(URL: fileURL) else { + public init(fileURL: URL, name: String, mimeType: String? = nil, fileName: String? = nil) throws { + guard let inputStream = InputStream(url: fileURL) else { throw Error.IllegalFileURL(fileURL) } - let fileSize = fileURL.path - .flatMap { try? NSFileManager.defaultManager().attributesOfItemAtPath($0) } - .flatMap { $0[NSFileSize] as? NSNumber } - .map { $0.integerValue } + let fileSize = (try? FileManager.default.attributesOfItem(atPath: fileURL.path)) + .flatMap { $0[FileAttributeKey.size] as? NSNumber } + .map { $0.intValue } guard let bodyLength = fileSize else { throw Error.CannotGetFileSize(fileURL) } - let detectedMimeType = fileURL.pathExtension - .flatMap { UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, $0, nil)?.takeRetainedValue() } + let detectedMimeType = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, fileURL.pathExtension, nil) + .map { $0.takeRetainedValue() } .flatMap { UTTypeCopyPreferredTagWithClass($0, kUTTagClassMIMEType)?.takeRetainedValue() } .map { $0 as String } @@ -118,8 +117,8 @@ public extension MultipartFormDataBodyParameters { } internal class PartInputStream: AbstractInputStream { - let headerData: NSData - let footerData: NSData + let headerData: Data + let footerData: Data let bodyPart: Part let totalLength: Int @@ -138,33 +137,33 @@ public extension MultipartFormDataBodyParameters { header = "--\(boundary)\r\nContent-Disposition: form-data; name=\"\(part.name)\"\r\n\r\n" } - headerData = header.dataUsingEncoding(NSUTF8StringEncoding)! - footerData = "\r\n".dataUsingEncoding(NSUTF8StringEncoding)! + headerData = header.data(using: .utf8)! + footerData = "\r\n".data(using: .utf8)! bodyPart = part - totalLength = headerData.length + bodyPart.length + footerData.length + totalLength = headerData.count + bodyPart.length + footerData.count totalSentLength = 0 super.init() } var headerRange: Range { - return 0.. { - return headerRange.endIndex..<(headerRange.endIndex + bodyPart.length) + return headerRange.upperBound..<(headerRange.upperBound + bodyPart.length) } var footerRange: Range { - return bodyRange.endIndex..<(bodyRange.endIndex + footerData.length) + return bodyRange.upperBound..<(bodyRange.upperBound + footerData.count) } - // MARK: NSInputStream + // MARK: InputStream override var hasBytesAvailable: Bool { return totalSentLength < totalLength } - override func read(buffer: UnsafeMutablePointer, maxLength: Int) -> Int { + override func read(_ buffer: UnsafeMutablePointer, maxLength: Int) -> Int { var sentLength = 0 while sentLength < maxLength && totalSentLength < totalLength { @@ -173,14 +172,14 @@ public extension MultipartFormDataBodyParameters { switch totalSentLength { case headerRange: - let readLength = min(headerRange.endIndex - totalSentLength, availableLength) - let readRange = NSRange(location: totalSentLength - headerRange.startIndex, length: readLength) - headerData.getBytes(offsetBuffer, range: readRange) + let readLength = min(headerRange.upperBound - totalSentLength, availableLength) + let readRange = NSRange(location: totalSentLength - headerRange.lowerBound, length: readLength) + (headerData as NSData).getBytes(offsetBuffer, range: readRange) sentLength += readLength totalSentLength += sentLength case bodyRange: - if bodyPart.inputStream.streamStatus == .NotOpen { + if bodyPart.inputStream.streamStatus == .notOpen { bodyPart.inputStream.open() } @@ -189,14 +188,14 @@ public extension MultipartFormDataBodyParameters { totalSentLength += readLength case footerRange: - let readLength = min(footerRange.endIndex - totalSentLength, availableLength) - let range = NSRange(location: totalSentLength - footerRange.startIndex, length: readLength) - footerData.getBytes(offsetBuffer, range: range) + let readLength = min(footerRange.upperBound - totalSentLength, availableLength) + let range = NSRange(location: totalSentLength - footerRange.lowerBound, length: readLength) + (footerData as NSData).getBytes(offsetBuffer, range: range) sentLength += readLength totalSentLength += readLength default: - print("Illegal range access: \(totalSentLength) is out of \(headerRange.startIndex)..<\(footerRange.endIndex)") + print("Illegal range access: \(totalSentLength) is out of \(headerRange.lowerBound)..<\(footerRange.upperBound)") return -1 } } @@ -208,18 +207,18 @@ public extension MultipartFormDataBodyParameters { internal class MultipartInputStream: AbstractInputStream { let boundary: String let partStreams: [PartInputStream] - let footerData: NSData + let footerData: Data let totalLength: Int var totalSentLength: Int - private var privateStreamStatus = NSStreamStatus.NotOpen + private var privateStreamStatus = Stream.Status.notOpen init(parts: [Part], boundary: String) { self.boundary = boundary self.partStreams = parts.map { PartInputStream(part: $0, boundary: boundary) } - self.footerData = "--\(boundary)--\r\n".dataUsingEncoding(NSUTF8StringEncoding)! - self.totalLength = partStreams.reduce(footerData.length) { $0 + $1.totalLength } + self.footerData = "--\(boundary)--\r\n".data(using: .utf8)! + self.totalLength = partStreams.reduce(footerData.count) { $0 + $1.totalLength } self.totalSentLength = 0 super.init() } @@ -229,7 +228,7 @@ public extension MultipartFormDataBodyParameters { } var footerRange: Range { - return partsRange.endIndex..<(partsRange.endIndex + footerData.length) + return partsRange.upperBound..<(partsRange.upperBound + footerData.count) } var currentPartInputStream: PartInputStream? { @@ -247,9 +246,9 @@ public extension MultipartFormDataBodyParameters { return nil } - // MARK: NSInputStream - // NOTE: NSInputStream does not have its own implementation because it is a class cluster. - override var streamStatus: NSStreamStatus { + // MARK: InputStream + // NOTE: InputStream does not have its own implementation because it is a class cluster. + override var streamStatus: Stream.Status { return privateStreamStatus } @@ -258,15 +257,15 @@ public extension MultipartFormDataBodyParameters { } override func open() { - privateStreamStatus = .Open + privateStreamStatus = .open } override func close() { - privateStreamStatus = .Closed + privateStreamStatus = .closed } - override func read(buffer: UnsafeMutablePointer, maxLength: Int) -> Int { - privateStreamStatus = .Reading + override func read(_ buffer: UnsafeMutablePointer, maxLength: Int) -> Int { + privateStreamStatus = .reading var sentLength = 0 @@ -286,35 +285,35 @@ public extension MultipartFormDataBodyParameters { totalSentLength += readLength case footerRange: - let readLength = min(footerRange.endIndex - totalSentLength, availableLength) - let range = NSRange(location: totalSentLength - footerRange.startIndex, length: readLength) - footerData.getBytes(offsetBuffer, range: range) + let readLength = min(footerRange.upperBound - totalSentLength, availableLength) + let range = NSRange(location: totalSentLength - footerRange.lowerBound, length: readLength) + (footerData as NSData).getBytes(offsetBuffer, range: range) sentLength += readLength totalSentLength += readLength default: - print("Illegal range access: \(totalSentLength) is out of \(partsRange.startIndex)..<\(footerRange.endIndex)") + print("Illegal range access: \(totalSentLength) is out of \(partsRange.lowerBound)..<\(footerRange.upperBound)") return -1 } - if privateStreamStatus != .Closed && !hasBytesAvailable { - privateStreamStatus = .AtEnd + if privateStreamStatus != .closed && !hasBytesAvailable { + privateStreamStatus = .atEnd } } return sentLength } - override var delegate: NSStreamDelegate? { + override var delegate: StreamDelegate? { get { return nil } set { } } - override func scheduleInRunLoop(runLoop: NSRunLoop, forMode mode: String) { + override func schedule(in aRunLoop: RunLoop, forMode mode: RunLoopMode) { } - override func removeFromRunLoop(runLoop: NSRunLoop, forMode mode: String) { + override func remove(from aRunLoop: RunLoop, forMode mode: RunLoopMode) { } } diff --git a/Sources/BodyParametersType/NSData+NSInputStream.swift b/Sources/BodyParametersType/NSData+NSInputStream.swift index fe722add..54549461 100644 --- a/Sources/BodyParametersType/NSData+NSInputStream.swift +++ b/Sources/BodyParametersType/NSData+NSInputStream.swift @@ -1,18 +1,16 @@ import Foundation -enum InputStreamError: ErrorType { +enum InputStreamError: Error { case InvalidDataCapacity(Int) - case UnreadableStream(NSInputStream) + case UnreadableStream(InputStream) } -extension NSData { - convenience init(inputStream: NSInputStream, capacity: Int = Int(UInt16.max)) throws { - guard let data = NSMutableData(capacity: capacity) else { - throw InputStreamError.InvalidDataCapacity(capacity) - } +extension Data { + init(inputStream: InputStream, capacity: Int = Int(UInt16.max)) throws { + var data = Data(capacity: capacity) - let bufferSize = min(Int(UInt16.max), capacity) - let buffer = UnsafeMutablePointer.alloc(bufferSize) + let bufferSize = _min(Int(UInt16.max), capacity) + let buffer = UnsafeMutablePointer.allocate(capacity: bufferSize) var readSize: Int @@ -21,7 +19,7 @@ extension NSData { switch readSize { case let x where x > 0: - data.appendBytes(buffer, length: readSize) + data.append(buffer, count: readSize) case let x where x < 0: throw InputStreamError.UnreadableStream(inputStream) @@ -31,8 +29,12 @@ extension NSData { } } while readSize > 0 - buffer.dealloc(bufferSize) + buffer.deallocate(capacity: bufferSize) - self.init(data: data) + self.init(data) } } + +private func _min(_ x: Int, _ y: Int) -> Int { + return y < x ? y : x +} diff --git a/Sources/CallbackQueue.swift b/Sources/CallbackQueue.swift index 59352d05..6964122f 100644 --- a/Sources/CallbackQueue.swift +++ b/Sources/CallbackQueue.swift @@ -9,15 +9,15 @@ public enum CallbackQueue { case SessionQueue /// Dispatches callback closure on associated operation queue. - case OperationQueue(NSOperationQueue) + case OperationQueue(OperationQueue) /// Dispatches callback closure on associated dispatch queue. - case DispatchQueue(dispatch_queue_t) + case DispatchQueue(Foundation.DispatchQueue) internal func execute(closure: () -> Void) { switch self { case .Main: - dispatch_async(dispatch_get_main_queue()) { + Foundation.DispatchQueue.main.async { closure() } @@ -25,12 +25,12 @@ public enum CallbackQueue { closure() case .OperationQueue(let operationQueue): - operationQueue.addOperationWithBlock { + operationQueue.addOperation { closure() } case .DispatchQueue(let dispatchQueue): - dispatch_async(dispatchQueue) { + dispatchQueue.async { closure() } } diff --git a/Sources/DataParserType/DataParserType.swift b/Sources/DataParserType/DataParserType.swift index 0777043b..4ee059d8 100644 --- a/Sources/DataParserType/DataParserType.swift +++ b/Sources/DataParserType/DataParserType.swift @@ -7,5 +7,5 @@ public protocol DataParserType { /// Return `AnyObject` that expresses structure of response such as JSON and XML. /// - Throws: `ErrorType` when parser encountered invalid format data. - func parseData(data: NSData) throws -> AnyObject + func parseData(_ data: Data) throws -> AnyObject } diff --git a/Sources/DataParserType/FormURLEncodedDataParser.swift b/Sources/DataParserType/FormURLEncodedDataParser.swift index 536033b0..e032868f 100644 --- a/Sources/DataParserType/FormURLEncodedDataParser.swift +++ b/Sources/DataParserType/FormURLEncodedDataParser.swift @@ -2,15 +2,15 @@ import Foundation /// `FormURLEncodedDataParser` parses form URL encoded response data. public class FormURLEncodedDataParser: DataParserType { - public enum Error: ErrorType { - case CannotGetStringFromData(NSData) + public enum Error: Swift.Error { + case CannotGetStringFromData(Data) } /// The string encoding of the data. - public let encoding: NSStringEncoding + public let encoding: String.Encoding /// Returns `FormURLEncodedDataParser` with the string encoding. - public init(encoding: NSStringEncoding) { + public init(encoding: String.Encoding) { self.encoding = encoding } @@ -22,13 +22,13 @@ public class FormURLEncodedDataParser: DataParserType { } /// Return `AnyObject` that expresses structure of response. - /// - Throws: `FormURLEncodedDataParser.Error` when the parser fails to initialize `NSString` from `NSData`. - public func parseData(data: NSData) throws -> AnyObject { - guard let string = NSString(data: data, encoding: encoding) as? String else { + /// - Throws: `FormURLEncodedDataParser.Error` when the parser fails to initialize `String` from `Data`. + public func parseData(_ data: Data) throws -> AnyObject { + guard let string = String(data: data, encoding: encoding) else { throw Error.CannotGetStringFromData(data) } - let components = NSURLComponents() + var components = URLComponents() components.percentEncodedQuery = string let queryItems = components.queryItems ?? [] diff --git a/Sources/DataParserType/JSONDataParser.swift b/Sources/DataParserType/JSONDataParser.swift index 227ea1fd..c64d1757 100644 --- a/Sources/DataParserType/JSONDataParser.swift +++ b/Sources/DataParserType/JSONDataParser.swift @@ -3,10 +3,10 @@ import Foundation /// `JSONDataParser` response JSON data. public class JSONDataParser: DataParserType { /// Options for reading the JSON data and creating the objects. - public let readingOptions: NSJSONReadingOptions + public let readingOptions: JSONSerialization.ReadingOptions /// Returns `JSONDataParser` with the reading options. - public init(readingOptions: NSJSONReadingOptions) { + public init(readingOptions: JSONSerialization.ReadingOptions) { self.readingOptions = readingOptions } @@ -18,12 +18,12 @@ public class JSONDataParser: DataParserType { } /// Return `AnyObject` that expresses structure of JSON response. - /// - Throws: `NSError` when `NSJSONSerialization` fails to deserialize `NSData` into `AnyObject`. - public func parseData(data: NSData) throws -> AnyObject { - guard data.length > 0 else { + /// - Throws: `NSError` when `JSONSerialization` fails to deserialize `Data` into `AnyObject`. + public func parseData(_ data: Data) throws -> AnyObject { + guard data.count > 0 else { return [:] } - return try NSJSONSerialization.JSONObjectWithData(data, options: readingOptions) + return try JSONSerialization.jsonObject(with: data, options: readingOptions) } } diff --git a/Sources/DataParserType/StringDataParser.swift b/Sources/DataParserType/StringDataParser.swift index aa54a014..36956927 100644 --- a/Sources/DataParserType/StringDataParser.swift +++ b/Sources/DataParserType/StringDataParser.swift @@ -2,15 +2,15 @@ import Foundation /// `StringDataParser` parses data and convert it to string. public class StringDataParser: DataParserType { - public enum Error: ErrorType { - case InvalidData(NSData) + public enum Error: Swift.Error { + case InvalidData(Data) } /// The string encoding of the data. - public let encoding: NSStringEncoding + public let encoding: String.Encoding /// Returns `FormURLEncodedDataParser` with the string encoding. - public init(encoding: NSStringEncoding = NSUTF8StringEncoding) { + public init(encoding: String.Encoding = .utf8) { self.encoding = encoding } @@ -21,10 +21,10 @@ public class StringDataParser: DataParserType { return nil } - /// Return `String` that converted from `NSData`. - /// - Throws: `StringDataParser.Error` when the parser fails to initialize `NSString` from `NSData`. - public func parseData(data: NSData) throws -> AnyObject { - guard let string = NSString(data: data, encoding: encoding) else { + /// Return `String` that converted from `Data`. + /// - Throws: `StringDataParser.Error` when the parser fails to initialize `String` from `Data`. + public func parseData(_ data: Data) throws -> AnyObject { + guard let string = String(data: data, encoding: encoding) else { throw Error.InvalidData(data) } diff --git a/Sources/Error/RequestError.swift b/Sources/Error/RequestError.swift index 222ff38d..ded40ee2 100644 --- a/Sources/Error/RequestError.swift +++ b/Sources/Error/RequestError.swift @@ -1,10 +1,10 @@ import Foundation -/// `RequestError` represents a common error that occurs while building `NSURLRequest` from `RequestType`. -public enum RequestError: ErrorType { +/// `RequestError` represents a common error that occurs while building `URLRequest` from `RequestType`. +public enum RequestError: Error { /// Indicates `baseURL` of a type that conforms `RequestType` is invalid. - case InvalidBaseURL(NSURL) + case InvalidBaseURL(URL) - /// Indicates `NSURLRequest` built by `RequestType.buildURLRequest` is unexpected. - case UnexpectedURLRequest(NSURLRequest) + /// Indicates `URLRequest` built by `RequestType.buildURLRequest` is unexpected. + case UnexpectedURLRequest(URLRequest) } diff --git a/Sources/Error/ResponseError.swift b/Sources/Error/ResponseError.swift index ef0a5c72..cd061611 100644 --- a/Sources/Error/ResponseError.swift +++ b/Sources/Error/ResponseError.swift @@ -1,12 +1,12 @@ import Foundation /// `ResponseError` represents a common error that occurs while getting `RequestType.Response` -/// from raw result tuple `(NSData?, NSURLResponse?, NSError?)`. -public enum ResponseError: ErrorType { - /// Indicates the session adapter returned `NSURLResponse` that fails to down-cast to `NSHTTPURLResponse`. - case NonHTTPURLResponse(NSURLResponse?) +/// from raw result tuple `(Data?, URLResponse?, NSError?)`. +public enum ResponseError: Error { + /// Indicates the session adapter returned `URLResponse` that fails to down-cast to `HTTPURLResponse`. + case NonHTTPURLResponse(URLResponse?) - /// Indicates `NSHTTPURLResponse.statusCode` is not acceptable. + /// Indicates `HTTPURLResponse.statusCode` is not acceptable. /// In most cases, *acceptable* means the value is in `200..<300`. case UnacceptableStatusCode(Int) diff --git a/Sources/Error/SessionTaskError.swift b/Sources/Error/SessionTaskError.swift index 7a31fa4c..d10c4ba7 100644 --- a/Sources/Error/SessionTaskError.swift +++ b/Sources/Error/SessionTaskError.swift @@ -1,13 +1,13 @@ import Foundation /// `SessionTaskError` represents an error that occurs while task for a request. -public enum SessionTaskError: ErrorType { - /// Error of `NSURLSession`. - case ConnectionError(ErrorType) +public enum SessionTaskError: Error { + /// Error of `URLSession`. + case ConnectionError(Error) - /// Error while creating `NSURLReqeust` from `Request`. - case RequestError(ErrorType) + /// Error while creating `URLReqeust` from `Request`. + case RequestError(Error) - /// Error while creating `RequestType.Response` from `(NSData, NSURLResponse)`. - case ResponseError(ErrorType) + /// Error while creating `RequestType.Response` from `(Data, URLResponse)`. + case ResponseError(Error) } diff --git a/Sources/RequestType.swift b/Sources/RequestType.swift index 04a05c1a..abbe4891 100644 --- a/Sources/RequestType.swift +++ b/Sources/RequestType.swift @@ -4,16 +4,16 @@ import Result /// `RequestType` protocol represents a request for Web API. /// Following 5 items must be implemented. /// - `typealias Response` -/// - `var baseURL: NSURL` +/// - `var baseURL: URL` /// - `var method: HTTPMethod` /// - `var path: String` -/// - `func responseFromObject(object: AnyObject, URLResponse: NSHTTPURLResponse) throws -> Response` +/// - `func responseFromObject(object: AnyObject, urlResponse: HTTPURLResponse) throws -> Response` public protocol RequestType { /// The response type associated with the request type. associatedtype Response /// The base URL. - var baseURL: NSURL { get } + var baseURL: URL { get } /// The HTTP request method. var method: HTTPMethod { get } @@ -43,22 +43,22 @@ public protocol RequestType { /// The parser object that states `Content-Type` to accept and parses response body. var dataParser: DataParserType { get } - /// Intercepts `NSURLRequest` which is created by `RequestType.buildURLRequest()`. If an error is + /// Intercepts `URLRequest` which is created by `RequestType.buildURLRequest()`. If an error is /// thrown in this method, the result of `Session.sendRequest()` turns `.Failure(.RequestError(error))`. /// - Throws: `ErrorType` - func interceptURLRequest(URLRequest: NSMutableURLRequest) throws -> NSMutableURLRequest + func interceptURLRequest(_ urlRequest: URLRequest) throws -> URLRequest - /// Intercepts response `AnyObject` and `NSHTTPURLResponse`. If an error is thrown in this method, + /// Intercepts response `AnyObject` and `HTTPURLResponse`. If an error is thrown in this method, /// the result of `Session.sendRequest()` turns `.Failure(.ResponseError(error))`. /// The default implementation of this method is provided to throw `RequestError.UnacceptableStatusCode` /// if the HTTP status code is not in `200..<300`. /// - Throws: `ErrorType` - func interceptObject(object: AnyObject, URLResponse: NSHTTPURLResponse) throws -> AnyObject + func interceptObject(_ object: AnyObject, urlResponse: HTTPURLResponse) throws -> AnyObject /// Build `Response` instance from raw response object. This method is called after /// `interceptObject(:URLResponse:)` if it does not throw any error. /// - Throws: `ErrorType` - func responseFromObject(object: AnyObject, URLResponse: NSHTTPURLResponse) throws -> Response + func responseFromObject(_ object: AnyObject, urlResponse: HTTPURLResponse) throws -> Response } public extension RequestType { @@ -67,7 +67,7 @@ public extension RequestType { } public var queryParameters: [String: AnyObject]? { - guard let parameters = parameters as? [String: AnyObject] where method.prefersQueryParameters else { + guard let parameters = parameters as? [String: AnyObject], method.prefersQueryParameters else { return nil } @@ -75,7 +75,7 @@ public extension RequestType { } public var bodyParameters: BodyParametersType? { - guard let parameters = parameters where !method.prefersQueryParameters else { + guard let parameters = parameters, !method.prefersQueryParameters else { return nil } @@ -90,65 +90,58 @@ public extension RequestType { return JSONDataParser(readingOptions: []) } - public func interceptURLRequest(URLRequest: NSMutableURLRequest) throws -> NSMutableURLRequest { - return URLRequest + public func interceptURLRequest(_ urlRequest: URLRequest) throws -> URLRequest { + return urlRequest } - public func interceptObject(object: AnyObject, URLResponse: NSHTTPURLResponse) throws -> AnyObject { - guard (200..<300).contains(URLResponse.statusCode) else { - throw ResponseError.UnacceptableStatusCode(URLResponse.statusCode) + public func interceptObject(_ object: AnyObject, urlResponse: HTTPURLResponse) throws -> AnyObject { + guard (200..<300).contains(urlResponse.statusCode) else { + throw ResponseError.UnacceptableStatusCode(urlResponse.statusCode) } return object } - /// Builds `NSURLRequest` from properties of `self`. + /// Builds `URLRequest` from properties of `self`. /// - Throws: `RequestError`, `ErrorType` - public func buildURLRequest() throws -> NSURLRequest { - let URL = path.isEmpty ? baseURL : baseURL.URLByAppendingPathComponent(path) - #if swift(>=2.3) - guard let unwrapped = URL, components = NSURLComponents(URL: unwrapped, resolvingAgainstBaseURL: true) else { - throw RequestError.InvalidBaseURL(baseURL) - } - #else - guard let components = NSURLComponents(URL: URL, resolvingAgainstBaseURL: true) else { - throw RequestError.InvalidBaseURL(baseURL) - } - #endif + public func buildURLRequest() throws -> URLRequest { + let url = path.isEmpty ? baseURL : baseURL.appendingPathComponent(path) + guard var components = URLComponents(url: url, resolvingAgainstBaseURL: true) else { + throw RequestError.InvalidBaseURL(baseURL) + } - let URLRequest = NSMutableURLRequest() + var urlRequest = URLRequest(url: url) - if let queryParameters = queryParameters where !queryParameters.isEmpty { + if let queryParameters = queryParameters, !queryParameters.isEmpty { components.percentEncodedQuery = URLEncodedSerialization.stringFromDictionary(queryParameters) } if let bodyParameters = bodyParameters { - URLRequest.setValue(bodyParameters.contentType, forHTTPHeaderField: "Content-Type") + urlRequest.setValue(bodyParameters.contentType, forHTTPHeaderField: "Content-Type") switch try bodyParameters.buildEntity() { case .Data(let data): - URLRequest.HTTPBody = data + urlRequest.httpBody = data case .InputStream(let inputStream): - URLRequest.HTTPBodyStream = inputStream + urlRequest.httpBodyStream = inputStream } } - URLRequest.URL = components.URL - URLRequest.HTTPMethod = method.rawValue - URLRequest.setValue(dataParser.contentType, forHTTPHeaderField: "Accept") + urlRequest.httpMethod = method.rawValue + urlRequest.setValue(dataParser.contentType, forHTTPHeaderField: "Accept") headerFields.forEach { key, value in - URLRequest.setValue(value, forHTTPHeaderField: key) + urlRequest.setValue(value, forHTTPHeaderField: key) } - return (try interceptURLRequest(URLRequest)) + return (try interceptURLRequest(urlRequest) as URLRequest) } - /// Builds `Response` from response `NSData`. + /// Builds `Response` from response `Data`. /// - Throws: `ResponseError`, `ErrorType` - public func parseData(data: NSData, URLResponse: NSHTTPURLResponse) throws -> Response { + public func parseData(_ data: Data, urlResponse: HTTPURLResponse) throws -> Response { let parsedObject = try dataParser.parseData(data) - let passedObject = try interceptObject(parsedObject, URLResponse: URLResponse) - return try responseFromObject(passedObject, URLResponse: URLResponse) + let passedObject = try interceptObject(parsedObject, urlResponse: urlResponse) + return try responseFromObject(passedObject, urlResponse: urlResponse) } } diff --git a/Sources/Serializations/URLEncodedSerialization.swift b/Sources/Serializations/URLEncodedSerialization.swift index 7d8351c2..fe70e83f 100644 --- a/Sources/Serializations/URLEncodedSerialization.swift +++ b/Sources/Serializations/URLEncodedSerialization.swift @@ -1,15 +1,15 @@ import Foundation -private func escape(string: String) -> String { +private func escape(_ string: String) -> String { // Reserved characters defined by RFC 3986 // Reference: https://www.ietf.org/rfc/rfc3986.txt let generalDelimiters = ":#[]@" let subDelimiters = "!$&'()*+,;=" let reservedCharacters = generalDelimiters + subDelimiters - let allowedCharacterSet = NSMutableCharacterSet() - allowedCharacterSet.formUnionWithCharacterSet(NSCharacterSet.URLQueryAllowedCharacterSet()) - allowedCharacterSet.removeCharactersInString(reservedCharacters) + var allowedCharacterSet = CharacterSet() + allowedCharacterSet.formUnion(.urlQueryAllowed) + allowedCharacterSet.remove(charactersIn: reservedCharacters) // Crashes due to internal bug in iOS 7 ~ iOS 8.2. // References: @@ -24,12 +24,12 @@ private func escape(string: String) -> String { while index != string.endIndex { let startIndex = index - let endIndex = index.advancedBy(batchSize, limit: string.endIndex) + let endIndex = string.index(index, offsetBy: batchSize, limitedBy: string.endIndex) ?? string.endIndex let range = startIndex.. String { return escaped } -private func unescape(string: String) -> String { +private func unescape(_ string: String) -> String { return CFURLCreateStringByReplacingPercentEscapes(nil, string, nil) as String } -/// `URLEncodedSerialization` parses `NSData` and `String` as urlencoded, +/// `URLEncodedSerialization` parses `Data` and `String` as urlencoded, /// and returns dictionary that represents the data or the string. public final class URLEncodedSerialization { - public enum Error: ErrorType { - case CannotGetStringFromData(NSData, NSStringEncoding) - case CannotGetDataFromString(String, NSStringEncoding) + public enum Error: Swift.Error { + case CannotGetStringFromData(Data, String.Encoding) + case CannotGetDataFromString(String, String.Encoding) case CannotCastObjectToDictionary(AnyObject) case InvalidFormatString(String) } - /// Returns `[String: String]` that represents urlencoded `NSData`. + /// Returns `[String: String]` that represents urlencoded `Data`. /// - Throws: URLEncodedSerialization.Error - public static func objectFromData(data: NSData, encoding: NSStringEncoding) throws -> [String: String] { + public static func objectFromData(data: Data, encoding: String.Encoding) throws -> [String: String] { guard let string = String(data: data, encoding: encoding) else { throw Error.CannotGetStringFromData(data, encoding) } var dictionary = [String: String]() - for pair in string.componentsSeparatedByString("&") { - let contents = pair.componentsSeparatedByString("=") + for pair in string.components(separatedBy: "&") { + let contents = pair.components(separatedBy: "=") guard contents.count == 2 else { throw Error.InvalidFormatString(string) @@ -72,23 +72,23 @@ public final class URLEncodedSerialization { return dictionary } - /// Returns urlencoded `NSData` from the object. + /// Returns urlencoded `Data` from the object. /// - Throws: URLEncodedSerialization.Error - public static func dataFromObject(object: AnyObject, encoding: NSStringEncoding) throws -> NSData { + public static func dataFromObject(_ object: AnyObject, encoding: String.Encoding) throws -> Data { guard let dictionary = object as? [String: AnyObject] else { throw Error.CannotCastObjectToDictionary(object) } let string = stringFromDictionary(dictionary) - guard let data = string.dataUsingEncoding(encoding, allowLossyConversion: false) else { + guard let data = string.data(using: encoding, allowLossyConversion: false) else { throw Error.CannotGetDataFromString(string, encoding) } return data } - /// Returns urlencoded `NSData` from the string. - public static func stringFromDictionary(dictionary: [String: AnyObject]) -> String { + /// Returns urlencoded `Data` from the string. + public static func stringFromDictionary(_ dictionary: [String: AnyObject]) -> String { let pairs = dictionary.map { key, value -> String in if value is NSNull { return "\(escape(key))" @@ -98,6 +98,6 @@ public final class URLEncodedSerialization { return "\(escape(key))=\(escape(valueAsString))" } - return pairs.joinWithSeparator("&") + return pairs.joined(separator: "&") } } diff --git a/Sources/Session.swift b/Sources/Session.swift index 5e91ba44..af1648d1 100644 --- a/Sources/Session.swift +++ b/Sources/Session.swift @@ -21,8 +21,8 @@ public class Session { // Shared session for class methods private static let privateSharedSession: Session = { - let configuration = NSURLSessionConfiguration.defaultSessionConfiguration() - let adapter = NSURLSessionAdapter(configuration: configuration) + let configuration = URLSessionConfiguration.default + let adapter = URLSessionAdapter(configuration: configuration) return Session(adapter: adapter) }() @@ -36,12 +36,12 @@ public class Session { /// - parameter callbackQueue: The queue where the handler runs. If this parameters is `nil`, default `callbackQueue` of `Session` will be used. /// - parameter handler: The closure that receives result of the request. /// - returns: The new session task. - public class func sendRequest(request: Request, callbackQueue: CallbackQueue? = nil, handler: (Result) -> Void = { _ in }) -> SessionTaskType? { + public class func sendRequest(_ request: Request, callbackQueue: CallbackQueue? = nil, handler: (Result) -> Void = { _ in }) -> SessionTaskType? { return sharedSession.sendRequest(request, callbackQueue: callbackQueue, handler: handler) } /// Calls `cancelRequest(_:passingTest:)` of `sharedSession`. - public class func cancelRequest(requestType: Request.Type, passingTest test: Request -> Bool = { _ in true }) { + public class func cancelRequest(_ requestType: Request.Type, passingTest test: (Request) -> Bool = { _ in true }) { sharedSession.cancelRequest(requestType, passingTest: test) } @@ -53,35 +53,35 @@ public class Session { /// - parameter callbackQueue: The queue where the handler runs. If this parameters is `nil`, default `callbackQueue` of `Session` will be used. /// - parameter handler: The closure that receives result of the request. /// - returns: The new session task. - public func sendRequest(request: Request, callbackQueue: CallbackQueue? = nil, handler: (Result) -> Void = { _ in }) -> SessionTaskType? { + public func sendRequest(_ request: Request, callbackQueue: CallbackQueue? = nil, handler: (Result) -> Void = { _ in }) -> SessionTaskType? { let callbackQueue = callbackQueue ?? self.callbackQueue - let URLRequest: NSURLRequest + let urlRequest: URLRequest do { - URLRequest = try request.buildURLRequest() + urlRequest = try request.buildURLRequest() } catch { callbackQueue.execute { - handler(.Failure(.RequestError(error))) + handler(.failure(.RequestError(error))) } return nil } - let task = adapter.createTaskWithURLRequest(URLRequest) { data, URLResponse, error in + let task = adapter.createTaskWithURLRequest(urlRequest) { data, urlResponse, error in let result: Result - switch (data, URLResponse, error) { + switch (data, urlResponse, error) { case (_, _, let error?): - result = .Failure(.ConnectionError(error)) + result = .failure(.ConnectionError(error)) - case (let data?, let URLResponse as NSHTTPURLResponse, _): + case (let data?, let urlResponse as HTTPURLResponse, _): do { - result = .Success(try request.parseData(data, URLResponse: URLResponse)) + result = .success(try request.parseData(data as Data, urlResponse: urlResponse)) } catch { - result = .Failure(.ResponseError(error)) + result = .failure(.ResponseError(error)) } default: - result = .Failure(.ResponseError(ResponseError.NonHTTPURLResponse(URLResponse))) + result = .failure(.ResponseError(ResponseError.NonHTTPURLResponse(urlResponse))) } callbackQueue.execute { @@ -98,7 +98,7 @@ public class Session { /// Cancels requests that passes the test. /// - parameter requestType: The request type to cancel. /// - parameter test: The test closure that determines if a request should be cancelled or not. - public func cancelRequest(requestType: Request.Type, passingTest test: Request -> Bool = { _ in true }) { + public func cancelRequest(_ requestType: Request.Type, passingTest test: (Request) -> Bool = { _ in true }) { adapter.getTasksWithHandler { [weak self] tasks in return tasks .filter { task in @@ -112,11 +112,11 @@ public class Session { } } - private func setRequest(request: Request, forTask task: SessionTaskType) { + private func setRequest(_ request: Request, forTask task: SessionTaskType) { objc_setAssociatedObject(task, &taskRequestKey, Box(request), .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } - private func requestForTask(task: SessionTaskType) -> Request? { + private func requestForTask(_ task: SessionTaskType) -> Request? { return (objc_getAssociatedObject(task, &taskRequestKey) as? Box)?.value } } diff --git a/Sources/SessionAdapterType/NSURLSessionAdapter.swift b/Sources/SessionAdapterType/NSURLSessionAdapter.swift deleted file mode 100644 index 3919d169..00000000 --- a/Sources/SessionAdapterType/NSURLSessionAdapter.swift +++ /dev/null @@ -1,75 +0,0 @@ -import Foundation - -extension NSURLSessionTask: SessionTaskType { - -} - -private var dataTaskResponseBufferKey = 0 -private var taskAssociatedObjectCompletionHandlerKey = 0 - -/// `NSURLSessionAdapter` connects `NSURLSession` with `Session`. -/// -/// If you want to add custom behavior of `NSURLSession` by implementing delegate methods defined in -/// `NSURLSessionDelegate` and related protocols, define a subclass of `NSURLSessionAdapter` and implment -/// delegate methods that you want to implement. Since `NSURLSessionAdapter` also implements delegate methods -/// `URLSession(_:task: didCompleteWithError:)` and `URLSession(_:dataTask:didReceiveData:)`, you have to call -/// `super` in these methods if you implement them. -public class NSURLSessionAdapter: NSObject, SessionAdapterType, NSURLSessionDelegate, NSURLSessionTaskDelegate, NSURLSessionDataDelegate { - /// The undelying `NSURLSession` instance. - public var URLSession: NSURLSession! - - /// Returns `NSURLSessionAdapter` initialized with `NSURLSessionConfiguration`. - public init(configuration: NSURLSessionConfiguration) { - super.init() - self.URLSession = NSURLSession(configuration: configuration, delegate: self, delegateQueue: nil) - } - - /// Creates `NSURLSessionDataTask` instance using `dataTaskWithRequest(_:completionHandler:)`. - public func createTaskWithURLRequest(URLRequest: NSURLRequest, handler: (NSData?, NSURLResponse?, ErrorType?) -> Void) -> SessionTaskType { - let task = URLSession.dataTaskWithRequest(URLRequest) - - setBuffer(NSMutableData(), forTask: task) - setHandler(handler, forTask: task) - - task.resume() - - return task - } - - /// Aggregates `NSURLSessionTask` instances in `URLSession` using `getTasksWithCompletionHandler(_:)`. - public func getTasksWithHandler(handler: [SessionTaskType] -> Void) { - URLSession.getTasksWithCompletionHandler { dataTasks, uploadTasks, downloadTasks in - let allTasks = dataTasks as [NSURLSessionTask] - + uploadTasks as [NSURLSessionTask] - + downloadTasks as [NSURLSessionTask] - - handler(allTasks.map { $0 }) - } - } - - private func setBuffer(buffer: NSMutableData, forTask task: NSURLSessionTask) { - objc_setAssociatedObject(task, &dataTaskResponseBufferKey, buffer, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) - } - - private func bufferForTask(task: NSURLSessionTask) -> NSMutableData? { - return objc_getAssociatedObject(task, &dataTaskResponseBufferKey) as? NSMutableData - } - - private func setHandler(handler: (NSData?, NSURLResponse?, NSError?) -> Void, forTask task: NSURLSessionTask) { - objc_setAssociatedObject(task, &taskAssociatedObjectCompletionHandlerKey, Box(handler), .OBJC_ASSOCIATION_RETAIN_NONATOMIC) - } - - private func handlerForTask(task: NSURLSessionTask) -> ((NSData?, NSURLResponse?, NSError?) -> Void)? { - return (objc_getAssociatedObject(task, &taskAssociatedObjectCompletionHandlerKey) as? Box<(NSData?, NSURLResponse?, NSError?) -> Void>)?.value - } - - // MARK: NSURLSessionTaskDelegate - public func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError connectionError: NSError?) { - handlerForTask(task)?(bufferForTask(task), task.response, connectionError) - } - - // MARK: NSURLSessionDataDelegate - public func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) { - bufferForTask(dataTask)?.appendData(data) - } -} diff --git a/Sources/SessionAdapterType/SessionAdapterType.swift b/Sources/SessionAdapterType/SessionAdapterType.swift index 46f4cde2..7e8510a2 100644 --- a/Sources/SessionAdapterType/SessionAdapterType.swift +++ b/Sources/SessionAdapterType/SessionAdapterType.swift @@ -7,12 +7,12 @@ public protocol SessionTaskType: class { } /// `SessionAdapterType` protocol provides interface to connect lower level networking backend with `Session`. -/// APIKit provides `NSURLSessionAdapter`, which conforms to `SessionAdapterType`, to connect `NSURLSession` +/// APIKit provides `URLSessionAdapter`, which conforms to `SessionAdapterType`, to connect `URLSession` /// with `Session`. public protocol SessionAdapterType { /// Returns instance that conforms to `SessionTaskType`. `handler` must be called after success or failure. - func createTaskWithURLRequest(URLRequest: NSURLRequest, handler: (NSData?, NSURLResponse?, ErrorType?) -> Void) -> SessionTaskType + func createTaskWithURLRequest(_ URLRequest: URLRequest, handler: (NSData?, URLResponse?, Error?) -> Void) -> SessionTaskType /// Collects tasks from backend networking stack. `handler` must be called after collecting. - func getTasksWithHandler(handler: [SessionTaskType] -> Void) + func getTasksWithHandler(handler: ([SessionTaskType]) -> Void) } diff --git a/Sources/SessionAdapterType/URLSessionAdapter.swift b/Sources/SessionAdapterType/URLSessionAdapter.swift new file mode 100644 index 00000000..c65ce9d2 --- /dev/null +++ b/Sources/SessionAdapterType/URLSessionAdapter.swift @@ -0,0 +1,75 @@ +import Foundation + +extension URLSessionTask: SessionTaskType { + +} + +private var dataTaskResponseBufferKey = 0 +private var taskAssociatedObjectCompletionHandlerKey = 0 + +/// `URLSessionAdapter` connects `URLSession` with `Session`. +/// +/// If you want to add custom behavior of `URLSession` by implementing delegate methods defined in +/// `URLSessionDelegate` and related protocols, define a subclass of `URLSessionAdapter` and implment +/// delegate methods that you want to implement. Since `URLSessionAdapter` also implements delegate methods +/// `URLSession(_:task: didCompleteWithError:)` and `URLSession(_:dataTask:didReceiveData:)`, you have to call +/// `super` in these methods if you implement them. +public class URLSessionAdapter: NSObject, SessionAdapterType, URLSessionDelegate, URLSessionTaskDelegate, URLSessionDataDelegate { + /// The undelying `URLSession` instance. + public var urlSession: URLSession! + + /// Returns `URLSessionAdapter` initialized with `URLSessionConfiguration`. + public init(configuration: URLSessionConfiguration) { + super.init() + self.urlSession = URLSession(configuration: configuration, delegate: self, delegateQueue: nil) + } + + /// Creates `URLSessionDataTask` instance using `dataTaskWithRequest(_:completionHandler:)`. + public func createTaskWithURLRequest(_ URLRequest: URLRequest, handler: (NSData?, URLResponse?, Error?) -> Void) -> SessionTaskType { + let task = urlSession.dataTask(with: URLRequest) + + setBuffer(NSMutableData(), forTask: task) + setHandler(handler, forTask: task) + + task.resume() + + return task + } + + /// Aggregates `URLSessionTask` instances in `URLSession` using `getTasksWithCompletionHandler(_:)`. + public func getTasksWithHandler(handler: ([SessionTaskType]) -> Void) { + urlSession.getTasksWithCompletionHandler { dataTasks, uploadTasks, downloadTasks in + let allTasks = dataTasks as [URLSessionTask] + + uploadTasks as [URLSessionTask] + + downloadTasks as [URLSessionTask] + + handler(allTasks.map { $0 }) + } + } + + private func setBuffer(_ buffer: NSMutableData, forTask task: URLSessionTask) { + objc_setAssociatedObject(task, &dataTaskResponseBufferKey, buffer, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) + } + + private func bufferForTask(_ task: URLSessionTask) -> NSMutableData? { + return objc_getAssociatedObject(task, &dataTaskResponseBufferKey) as? NSMutableData + } + + private func setHandler(_ handler: (NSData?, URLResponse?, NSError?) -> Void, forTask task: URLSessionTask) { + objc_setAssociatedObject(task, &taskAssociatedObjectCompletionHandlerKey, Box(handler), .OBJC_ASSOCIATION_RETAIN_NONATOMIC) + } + + private func handlerForTask(_ task: URLSessionTask) -> ((NSData?, URLResponse?, NSError?) -> Void)? { + return (objc_getAssociatedObject(task, &taskAssociatedObjectCompletionHandlerKey) as? Box<(NSData?, URLResponse?, NSError?) -> Void>)?.value + } + + // MARK: URLSessionTaskDelegate + public func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { + handlerForTask(task)?(bufferForTask(task), task.response, error) + } + + // MARK: URLSessionDataDelegate + public func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) { + bufferForTask(dataTask)?.append(data) + } +} diff --git a/Tests/APIKit/TestComponents/TestRequest.swift b/Tests/APIKit/TestComponents/TestRequest.swift index a9e5ea31..45c63fd6 100644 --- a/Tests/APIKit/TestComponents/TestRequest.swift +++ b/Tests/APIKit/TestComponents/TestRequest.swift @@ -26,7 +26,7 @@ struct TestRequest: RequestType { let headerFields: [String: String] let interceptURLRequest: NSMutableURLRequest throws -> NSMutableURLRequest - func interceptURLRequest(URLRequest: NSMutableURLRequest) throws -> NSMutableURLRequest { + func interceptURLRequest(_ URLRequest: NSMutableURLRequest) throws -> NSMutableURLRequest { return try interceptURLRequest(URLRequest) } From 0b3032662b2a677a66f7e440860d4928a3194c4b Mon Sep 17 00:00:00 2001 From: Syo Ikeda Date: Mon, 8 Aug 2016 20:19:21 +0900 Subject: [PATCH 03/38] Test migration --- Demo.playground/Contents.swift | 4 +- Sources/RequestType.swift | 5 +- .../URLEncodedSerialization.swift | 2 +- Sources/Session.swift | 2 + .../SessionAdapterType.swift | 2 +- .../URLSessionAdapter.swift | 2 +- .../FormURLEncodedBodyParametersTests.swift | 2 +- .../JSONBodyParametersTests.swift | 4 +- .../MultipartFormDataParametersTests.swift | 40 ++-- .../URLEncodedSerializationTests.swift | 20 +- .../FormURLEncodedDataParserTests.swift | 12 +- .../DataParserType/JSONDataParserTests.swift | 2 +- .../StringDataParserTests.swift | 12 +- Tests/APIKit/RequestTypeTests.swift | 174 +++++++++--------- .../NSURLSessionAdapterSubclassTests.swift | 28 +-- .../NSURLSessionAdapterTests.swift | 42 ++--- Tests/APIKit/SessionCallbackQueueTests.swift | 46 ++--- Tests/APIKit/SessionTests.swift | 80 ++++---- Tests/APIKit/TestComponents/TestRequest.swift | 20 +- .../TestComponents/TestSessionAdapter.swift | 22 +-- .../TestComponents/TestSessionTask.swift | 4 +- 21 files changed, 264 insertions(+), 261 deletions(-) diff --git a/Demo.playground/Contents.swift b/Demo.playground/Contents.swift index 1f856dd9..8c15d89a 100644 --- a/Demo.playground/Contents.swift +++ b/Demo.playground/Contents.swift @@ -62,11 +62,11 @@ let request = GetRateLimitRequest() Session.sendRequest(request) { result in switch result { - case .Success(let rateLimit): + case .success(let rateLimit): print("count: \(rateLimit.count)") print("reset: \(rateLimit.resetDate)") - case .Failure(let error): + case .failure(let error): print("error: \(error)") } } diff --git a/Sources/RequestType.swift b/Sources/RequestType.swift index abbe4891..b817d65c 100644 --- a/Sources/RequestType.swift +++ b/Sources/RequestType.swift @@ -44,12 +44,12 @@ public protocol RequestType { var dataParser: DataParserType { get } /// Intercepts `URLRequest` which is created by `RequestType.buildURLRequest()`. If an error is - /// thrown in this method, the result of `Session.sendRequest()` turns `.Failure(.RequestError(error))`. + /// thrown in this method, the result of `Session.sendRequest()` turns `.failure(.RequestError(error))`. /// - Throws: `ErrorType` func interceptURLRequest(_ urlRequest: URLRequest) throws -> URLRequest /// Intercepts response `AnyObject` and `HTTPURLResponse`. If an error is thrown in this method, - /// the result of `Session.sendRequest()` turns `.Failure(.ResponseError(error))`. + /// the result of `Session.sendRequest()` turns `.failure(.ResponseError(error))`. /// The default implementation of this method is provided to throw `RequestError.UnacceptableStatusCode` /// if the HTTP status code is not in `200..<300`. /// - Throws: `ErrorType` @@ -127,6 +127,7 @@ public extension RequestType { } } + urlRequest.url = components.url urlRequest.httpMethod = method.rawValue urlRequest.setValue(dataParser.contentType, forHTTPHeaderField: "Accept") diff --git a/Sources/Serializations/URLEncodedSerialization.swift b/Sources/Serializations/URLEncodedSerialization.swift index fe70e83f..ed9f59e9 100644 --- a/Sources/Serializations/URLEncodedSerialization.swift +++ b/Sources/Serializations/URLEncodedSerialization.swift @@ -53,7 +53,7 @@ public final class URLEncodedSerialization { /// Returns `[String: String]` that represents urlencoded `Data`. /// - Throws: URLEncodedSerialization.Error - public static func objectFromData(data: Data, encoding: String.Encoding) throws -> [String: String] { + public static func objectFromData(_ data: Data, encoding: String.Encoding) throws -> [String: String] { guard let string = String(data: data, encoding: encoding) else { throw Error.CannotGetStringFromData(data, encoding) } diff --git a/Sources/Session.swift b/Sources/Session.swift index af1648d1..7f689f75 100644 --- a/Sources/Session.swift +++ b/Sources/Session.swift @@ -36,6 +36,7 @@ public class Session { /// - parameter callbackQueue: The queue where the handler runs. If this parameters is `nil`, default `callbackQueue` of `Session` will be used. /// - parameter handler: The closure that receives result of the request. /// - returns: The new session task. + @discardableResult public class func sendRequest(_ request: Request, callbackQueue: CallbackQueue? = nil, handler: (Result) -> Void = { _ in }) -> SessionTaskType? { return sharedSession.sendRequest(request, callbackQueue: callbackQueue, handler: handler) } @@ -53,6 +54,7 @@ public class Session { /// - parameter callbackQueue: The queue where the handler runs. If this parameters is `nil`, default `callbackQueue` of `Session` will be used. /// - parameter handler: The closure that receives result of the request. /// - returns: The new session task. + @discardableResult public func sendRequest(_ request: Request, callbackQueue: CallbackQueue? = nil, handler: (Result) -> Void = { _ in }) -> SessionTaskType? { let callbackQueue = callbackQueue ?? self.callbackQueue diff --git a/Sources/SessionAdapterType/SessionAdapterType.swift b/Sources/SessionAdapterType/SessionAdapterType.swift index 7e8510a2..a9920a50 100644 --- a/Sources/SessionAdapterType/SessionAdapterType.swift +++ b/Sources/SessionAdapterType/SessionAdapterType.swift @@ -14,5 +14,5 @@ public protocol SessionAdapterType { func createTaskWithURLRequest(_ URLRequest: URLRequest, handler: (NSData?, URLResponse?, Error?) -> Void) -> SessionTaskType /// Collects tasks from backend networking stack. `handler` must be called after collecting. - func getTasksWithHandler(handler: ([SessionTaskType]) -> Void) + func getTasksWithHandler(_ handler: ([SessionTaskType]) -> Void) } diff --git a/Sources/SessionAdapterType/URLSessionAdapter.swift b/Sources/SessionAdapterType/URLSessionAdapter.swift index c65ce9d2..249c941e 100644 --- a/Sources/SessionAdapterType/URLSessionAdapter.swift +++ b/Sources/SessionAdapterType/URLSessionAdapter.swift @@ -37,7 +37,7 @@ public class URLSessionAdapter: NSObject, SessionAdapterType, URLSessionDelegate } /// Aggregates `URLSessionTask` instances in `URLSession` using `getTasksWithCompletionHandler(_:)`. - public func getTasksWithHandler(handler: ([SessionTaskType]) -> Void) { + public func getTasksWithHandler(_ handler: ([SessionTaskType]) -> Void) { urlSession.getTasksWithCompletionHandler { dataTasks, uploadTasks, downloadTasks in let allTasks = dataTasks as [URLSessionTask] + uploadTasks as [URLSessionTask] diff --git a/Tests/APIKit/BodyParametersType/FormURLEncodedBodyParametersTests.swift b/Tests/APIKit/BodyParametersType/FormURLEncodedBodyParametersTests.swift index c823da25..1c360db4 100644 --- a/Tests/APIKit/BodyParametersType/FormURLEncodedBodyParametersTests.swift +++ b/Tests/APIKit/BodyParametersType/FormURLEncodedBodyParametersTests.swift @@ -14,7 +14,7 @@ class FormURLEncodedBodyParametersTests: XCTestCase { return } - let createdObject = try URLEncodedSerialization.objectFromData(data, encoding: NSUTF8StringEncoding) + let createdObject = try URLEncodedSerialization.objectFromData(data, encoding: .utf8) XCTAssertEqual(createdObject["foo"], "1") XCTAssertEqual(createdObject["bar"], "2") XCTAssertEqual(createdObject["baz"], "3") diff --git a/Tests/APIKit/BodyParametersType/JSONBodyParametersTests.swift b/Tests/APIKit/BodyParametersType/JSONBodyParametersTests.swift index c7d20d95..4bae4d46 100644 --- a/Tests/APIKit/BodyParametersType/JSONBodyParametersTests.swift +++ b/Tests/APIKit/BodyParametersType/JSONBodyParametersTests.swift @@ -14,7 +14,7 @@ class JSONBodyParametersTests: XCTestCase { return } - let dictionary = try NSJSONSerialization.JSONObjectWithData(data, options: []) + let dictionary = try JSONSerialization.jsonObject(with: data, options: []) XCTAssertEqual(dictionary["foo"], 1) XCTAssertEqual(dictionary["bar"], 2) XCTAssertEqual(dictionary["baz"], 3) @@ -28,7 +28,7 @@ class JSONBodyParametersTests: XCTestCase { let parameters = JSONBodyParameters(JSONObject: object) do { - try parameters.buildEntity() + try _ = parameters.buildEntity() XCTFail() } catch { let nserror = error as NSError diff --git a/Tests/APIKit/BodyParametersType/MultipartFormDataParametersTests.swift b/Tests/APIKit/BodyParametersType/MultipartFormDataParametersTests.swift index 7ce72fa6..21ff54dc 100644 --- a/Tests/APIKit/BodyParametersType/MultipartFormDataParametersTests.swift +++ b/Tests/APIKit/BodyParametersType/MultipartFormDataParametersTests.swift @@ -5,8 +5,8 @@ import XCTest class MultipartFormDataParametersTests: XCTestCase { // MARK: Entity func testDataEntitySuccess() { - let value1 = "1".dataUsingEncoding(NSUTF8StringEncoding)! - let value2 = "2".dataUsingEncoding(NSUTF8StringEncoding)! + let value1 = "1".data(using: .utf8)! + let value2 = "2".data(using: .utf8)! let parameters = MultipartFormDataBodyParameters(parts: [ MultipartFormDataBodyParameters.Part(data: value1, name: "foo"), @@ -19,16 +19,16 @@ class MultipartFormDataParametersTests: XCTestCase { return } - let encodedData = String(data: data, encoding:NSUTF8StringEncoding)! + let encodedData = String(data: data, encoding:.utf8)! let returnCode = "\r\n" let pattern = "^multipart/form-data; boundary=([\\w.]+)$" let regexp = try NSRegularExpression(pattern: pattern, options: []) let range = NSRange(location: 0, length: parameters.contentType.characters.count) - let match = regexp.matchesInString(parameters.contentType, options: [], range: range) + let match = regexp.matches(in: parameters.contentType, options: [], range: range) XCTAssertTrue(match.count > 0) - let boundary = (parameters.contentType as NSString).substringWithRange(match.first!.rangeAtIndex(1)) + let boundary = (parameters.contentType as NSString).substring(with: match.first!.rangeAt(1)) XCTAssertEqual(parameters.contentType, "multipart/form-data; boundary=\(boundary)") XCTAssertEqual(encodedData, "--\(boundary)\(returnCode)Content-Disposition: form-data; name=\"foo\"\(returnCode)\(returnCode)1\(returnCode)--\(boundary)\(returnCode)Content-Disposition: form-data; name=\"bar\"\(returnCode)\(returnCode)2\(returnCode)--\(boundary)--\(returnCode)") } catch { @@ -37,8 +37,8 @@ class MultipartFormDataParametersTests: XCTestCase { } func testInputStreamEntitySuccess() { - let value1 = "1".dataUsingEncoding(NSUTF8StringEncoding)! - let value2 = "2".dataUsingEncoding(NSUTF8StringEncoding)! + let value1 = "1".data(using: .utf8)! + let value2 = "2".data(using: .utf8)! let parameters = MultipartFormDataBodyParameters(parts: [ MultipartFormDataBodyParameters.Part(data: value1, name: "foo"), @@ -51,17 +51,17 @@ class MultipartFormDataParametersTests: XCTestCase { return } - let data = try NSData(inputStream: inputStream) - let encodedData = String(data: data, encoding:NSUTF8StringEncoding)! + let data = try Data(inputStream: inputStream) + let encodedData = String(data: data, encoding:.utf8)! let returnCode = "\r\n" let pattern = "^multipart/form-data; boundary=([\\w.]+)$" let regexp = try NSRegularExpression(pattern: pattern, options: []) let range = NSRange(location: 0, length: parameters.contentType.characters.count) - let match = regexp.matchesInString(parameters.contentType, options: [], range: range) + let match = regexp.matches(in: parameters.contentType, options: [], range: range) XCTAssertTrue(match.count > 0) - let boundary = (parameters.contentType as NSString).substringWithRange(match.first!.rangeAtIndex(1)) + let boundary = (parameters.contentType as NSString).substring(with: match.first!.rangeAt(1)) XCTAssertEqual(parameters.contentType, "multipart/form-data; boundary=\(boundary)") XCTAssertEqual(encodedData, "--\(boundary)\(returnCode)Content-Disposition: form-data; name=\"foo\"\(returnCode)\(returnCode)1\(returnCode)--\(boundary)\(returnCode)Content-Disposition: form-data; name=\"bar\"\(returnCode)\(returnCode)2\(returnCode)--\(boundary)--\(returnCode)") } catch { @@ -71,7 +71,7 @@ class MultipartFormDataParametersTests: XCTestCase { // MARK: Values func testFileValue() { - let fileURL = NSBundle(forClass: self.dynamicType).URLForResource("test", withExtension: "json")! + let fileURL = Bundle(for: self.dynamicType).url(forResource: "test", withExtension: "json")! let part = try! MultipartFormDataBodyParameters.Part(fileURL: fileURL, name: "test") let parameters = MultipartFormDataBodyParameters(parts: [part]) @@ -81,19 +81,19 @@ class MultipartFormDataParametersTests: XCTestCase { return } - let testData = NSData(contentsOfURL: fileURL)! - let testString = NSString(data: testData, encoding: NSUTF8StringEncoding)! + let testData = try! Data(contentsOf: fileURL) + let testString = String(data: testData, encoding: .utf8)! - let encodedData = String(data: data, encoding:NSUTF8StringEncoding)! + let encodedData = String(data: data, encoding:.utf8)! let returnCode = "\r\n" let pattern = "^multipart/form-data; boundary=([\\w.]+)$" let regexp = try NSRegularExpression(pattern: pattern, options: []) let range = NSRange(location: 0, length: parameters.contentType.characters.count) - let match = regexp.matchesInString(parameters.contentType, options: [], range: range) + let match = regexp.matches(in: parameters.contentType, options: [], range: range) XCTAssertTrue(match.count > 0) - let boundary = (parameters.contentType as NSString).substringWithRange(match.first!.rangeAtIndex(1)) + let boundary = (parameters.contentType as NSString).substring(with: match.first!.rangeAt(1)) XCTAssertEqual(parameters.contentType, "multipart/form-data; boundary=\(boundary)") XCTAssertEqual(encodedData, "--\(boundary)\(returnCode)Content-Disposition: form-data; name=\"test\"; filename=\"test.json\"\r\nContent-Type: application/json\(returnCode)\(returnCode)\(testString)\(returnCode)--\(boundary)--\(returnCode)") } catch { @@ -111,7 +111,7 @@ class MultipartFormDataParametersTests: XCTestCase { return } - let string = String(data: data, encoding:NSUTF8StringEncoding)! + let string = String(data: data, encoding:.utf8)! XCTAssertEqual(string, "--\(parameters.boundary)\r\nContent-Disposition: form-data; name=\"foo\"\r\n\r\nabcdef\r\n--\(parameters.boundary)--\r\n") } catch { XCTFail() @@ -128,7 +128,7 @@ class MultipartFormDataParametersTests: XCTestCase { return } - let string = String(data: data, encoding:NSUTF8StringEncoding)! + let string = String(data: data, encoding:.utf8)! XCTAssertEqual(string, "--\(parameters.boundary)\r\nContent-Disposition: form-data; name=\"foo\"\r\n\r\n123\r\n--\(parameters.boundary)--\r\n") } catch { XCTFail() @@ -145,7 +145,7 @@ class MultipartFormDataParametersTests: XCTestCase { return } - let string = String(data: data, encoding:NSUTF8StringEncoding)! + let string = String(data: data, encoding:.utf8)! XCTAssertEqual(string, "--\(parameters.boundary)\r\nContent-Disposition: form-data; name=\"foo\"\r\n\r\n3.14\r\n--\(parameters.boundary)--\r\n") } catch { XCTFail() diff --git a/Tests/APIKit/BodyParametersType/URLEncodedSerializationTests.swift b/Tests/APIKit/BodyParametersType/URLEncodedSerializationTests.swift index 8750178f..92bb272f 100644 --- a/Tests/APIKit/BodyParametersType/URLEncodedSerializationTests.swift +++ b/Tests/APIKit/BodyParametersType/URLEncodedSerializationTests.swift @@ -5,8 +5,8 @@ import APIKit class URLEncodedSerializationTests: XCTestCase { // MARK: NSData -> AnyObject func testObjectFromData() { - let data = "key1=value1&key2=value2".dataUsingEncoding(NSUTF8StringEncoding)! - let object = try? URLEncodedSerialization.objectFromData(data, encoding: NSUTF8StringEncoding) + let data = "key1=value1&key2=value2".data(using: .utf8)! + let object = try? URLEncodedSerialization.objectFromData(data, encoding: .utf8) XCTAssertEqual(object?["key1"], "value1") XCTAssertEqual(object?["key2"], "value2") } @@ -15,8 +15,8 @@ class URLEncodedSerializationTests: XCTestCase { let string = "key==value&" do { - let data = string.dataUsingEncoding(NSUTF8StringEncoding)! - try URLEncodedSerialization.objectFromData(data, encoding: NSUTF8StringEncoding) + let data = string.data(using: .utf8)! + try _ = URLEncodedSerialization.objectFromData(data, encoding: .utf8) XCTFail() } catch { guard let error = error as? URLEncodedSerialization.Error, @@ -31,10 +31,10 @@ class URLEncodedSerializationTests: XCTestCase { func testInvalidString() { var bytes = [UInt8]([0xed, 0xa0, 0x80]) // U+D800 (high surrogate) - let data = NSData(bytes: &bytes, length: bytes.count) + let data = Data(bytes: &bytes, count: bytes.count) do { - try URLEncodedSerialization.objectFromData(data, encoding: NSUTF8StringEncoding) + try _ = URLEncodedSerialization.objectFromData(data, encoding: .utf8) XCTFail() } catch { guard let error = error as? URLEncodedSerialization.Error, @@ -44,15 +44,15 @@ class URLEncodedSerializationTests: XCTestCase { } XCTAssertEqual(data, invalidData) - XCTAssertEqual(encoding, NSUTF8StringEncoding) + XCTAssertEqual(encoding, .utf8) } } // MARK: AnyObject -> NSData func testDataFromObject() { let object = ["hey": "yo"] as AnyObject - let data = try? URLEncodedSerialization.dataFromObject(object, encoding: NSUTF8StringEncoding) - let string = data.flatMap { NSString(data: $0, encoding: NSUTF8StringEncoding) } + let data = try? URLEncodedSerialization.dataFromObject(object, encoding: .utf8) + let string = data.flatMap { String(data: $0, encoding: .utf8) } XCTAssertEqual(string, "hey=yo") } @@ -60,7 +60,7 @@ class URLEncodedSerializationTests: XCTestCase { let dictionaries = [["hey": "yo"]] as AnyObject do { - try URLEncodedSerialization.dataFromObject(dictionaries, encoding: NSUTF8StringEncoding) + try _ = URLEncodedSerialization.dataFromObject(dictionaries, encoding: .utf8) XCTFail() } catch { guard let error = error as? URLEncodedSerialization.Error, diff --git a/Tests/APIKit/DataParserType/FormURLEncodedDataParserTests.swift b/Tests/APIKit/DataParserType/FormURLEncodedDataParserTests.swift index d7ab1d95..75c5b6a3 100644 --- a/Tests/APIKit/DataParserType/FormURLEncodedDataParserTests.swift +++ b/Tests/APIKit/DataParserType/FormURLEncodedDataParserTests.swift @@ -4,14 +4,14 @@ import XCTest class FormURLEncodedDataParserTests: XCTestCase { func testURLAcceptHeader() { - let parser = FormURLEncodedDataParser(encoding: NSUTF8StringEncoding) + let parser = FormURLEncodedDataParser(encoding: .utf8) XCTAssertEqual(parser.contentType, "application/x-www-form-urlencoded") } func testURLSuccess() { let string = "foo=1&bar=2&baz=3" - let data = string.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)! - let parser = FormURLEncodedDataParser(encoding: NSUTF8StringEncoding) + let data = string.data(using: .utf8, allowLossyConversion: false)! + let parser = FormURLEncodedDataParser(encoding: .utf8) do { let object = try parser.parseData(data) @@ -26,11 +26,11 @@ class FormURLEncodedDataParserTests: XCTestCase { func testInvalidString() { var bytes = [UInt8]([0xed, 0xa0, 0x80]) // U+D800 (high surrogate) - let data = NSData(bytes: &bytes, length: bytes.count) - let parser = FormURLEncodedDataParser(encoding: NSUTF8StringEncoding) + let data = Data(bytes: &bytes, count: bytes.count) + let parser = FormURLEncodedDataParser(encoding: .utf8) do { - try parser.parseData(data) + try _ = parser.parseData(data) XCTFail() } catch { guard let error = error as? FormURLEncodedDataParser.Error, diff --git a/Tests/APIKit/DataParserType/JSONDataParserTests.swift b/Tests/APIKit/DataParserType/JSONDataParserTests.swift index 10083ca5..ee417d6a 100644 --- a/Tests/APIKit/DataParserType/JSONDataParserTests.swift +++ b/Tests/APIKit/DataParserType/JSONDataParserTests.swift @@ -10,7 +10,7 @@ class JSONDataParserTests: XCTestCase { func testJSONSuccess() { let string = "{\"foo\": 1, \"bar\": 2, \"baz\": 3}" - let data = string.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)! + let data = string.data(using: .utf8, allowLossyConversion: false)! let parser = JSONDataParser(readingOptions: []) do { diff --git a/Tests/APIKit/DataParserType/StringDataParserTests.swift b/Tests/APIKit/DataParserType/StringDataParserTests.swift index cd7b77ca..a29d54d3 100644 --- a/Tests/APIKit/DataParserType/StringDataParserTests.swift +++ b/Tests/APIKit/DataParserType/StringDataParserTests.swift @@ -4,14 +4,14 @@ import APIKit class StringDataParserTests: XCTestCase { func testAcceptHeader() { - let parser = StringDataParser(encoding: NSUTF8StringEncoding) + let parser = StringDataParser(encoding: .utf8) XCTAssertNil(parser.contentType) } func testParseData() { let string = "abcdef" - let data = string.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)! - let parser = StringDataParser(encoding: NSUTF8StringEncoding) + let data = string.data(using: .utf8, allowLossyConversion: false)! + let parser = StringDataParser(encoding: .utf8) do { let object = try parser.parseData(data) @@ -23,11 +23,11 @@ class StringDataParserTests: XCTestCase { func testInvalidString() { var bytes = [UInt8]([0xed, 0xa0, 0x80]) // U+D800 (high surrogate) - let data = NSData(bytes: &bytes, length: bytes.count) - let parser = StringDataParser(encoding: NSUTF8StringEncoding) + let data = Data(bytes: &bytes, count: bytes.count) + let parser = StringDataParser(encoding: .utf8) do { - try parser.parseData(data) + try _ = parser.parseData(data) XCTFail() } catch { guard let error = error as? StringDataParser.Error, diff --git a/Tests/APIKit/RequestTypeTests.swift b/Tests/APIKit/RequestTypeTests.swift index 2b387ad7..2dfb56b7 100644 --- a/Tests/APIKit/RequestTypeTests.swift +++ b/Tests/APIKit/RequestTypeTests.swift @@ -4,28 +4,28 @@ import APIKit class RequestTypeTests: XCTestCase { func testJapanesesQueryParameters() { let request = TestRequest(parameters: ["q": "こんにちは"]) - let URLRequest = try? request.buildURLRequest() - XCTAssertEqual(URLRequest?.URL?.query, "q=%E3%81%93%E3%82%93%E3%81%AB%E3%81%A1%E3%81%AF") + let urlRequest = try? request.buildURLRequest() + XCTAssertEqual(urlRequest?.url?.query, "q=%E3%81%93%E3%82%93%E3%81%AB%E3%81%A1%E3%81%AF") } func testSymbolQueryParameters() { let request = TestRequest(parameters: ["q": "!\"#$%&'()0=~|`{}*+<>?/_"]) - let URLRequest = try? request.buildURLRequest() - XCTAssertEqual(URLRequest?.URL?.query, "q=%21%22%23%24%25%26%27%28%290%3D~%7C%60%7B%7D%2A%2B%3C%3E?/_") + let urlRequest = try? request.buildURLRequest() + XCTAssertEqual(urlRequest?.url?.query, "q=%21%22%23%24%25%26%27%28%290%3D~%7C%60%7B%7D%2A%2B%3C%3E?/_") } func testNullQueryParameters() { let request = TestRequest(parameters: ["null": NSNull()]) - let URLRequest = try? request.buildURLRequest() - XCTAssertEqual(URLRequest?.URL?.query, "null") + let urlRequest = try? request.buildURLRequest() + XCTAssertEqual(urlRequest?.url?.query, "null") } func testheaderFields() { let request = TestRequest(headerFields: ["Foo": "f", "Accept": "a", "Content-Type": "c"]) - let URLReqeust = try? request.buildURLRequest() - XCTAssertEqual(URLReqeust?.valueForHTTPHeaderField("Foo"), "f") - XCTAssertEqual(URLReqeust?.valueForHTTPHeaderField("Accept"), "a") - XCTAssertEqual(URLReqeust?.valueForHTTPHeaderField("Content-Type"), "c") + let urlReqeust = try? request.buildURLRequest() + XCTAssertEqual(urlReqeust?.value(forHTTPHeaderField: "Foo"), "f") + XCTAssertEqual(urlReqeust?.value(forHTTPHeaderField: "Accept"), "a") + XCTAssertEqual(urlReqeust?.value(forHTTPHeaderField: "Content-Type"), "c") } func testPOSTJSONRequest() { @@ -38,10 +38,10 @@ class RequestTypeTests: XCTestCase { let request = TestRequest(method: .POST, parameters: parameters) XCTAssert(request.parameters?.count == 3) - let URLRequest = try? request.buildURLRequest() - XCTAssertNotNil(URLRequest?.HTTPBody) + let urlRequest = try? request.buildURLRequest() + XCTAssertNotNil(urlRequest?.httpBody) - let json = URLRequest?.HTTPBody.flatMap { try? NSJSONSerialization.JSONObjectWithData($0, options: []) } as? [AnyObject] + let json = urlRequest?.httpBody.flatMap { try? JSONSerialization.jsonObject(with: $0, options: []) } as? [AnyObject] XCTAssertEqual(json?.count, 3) XCTAssertEqual(json?[0]["id"], "1") XCTAssertEqual(json?[1]["id"], "2") @@ -53,368 +53,368 @@ class RequestTypeTests: XCTestCase { func testPOSTInvalidJSONRequest() { let request = TestRequest(method: .POST, parameters: "foo") - let URLRequest = try? request.buildURLRequest() - XCTAssertNil(URLRequest?.HTTPBody) + let urlRequest = try? request.buildURLRequest() + XCTAssertNil(urlRequest?.httpBody) } func testBuildURL() { // MARK: - baseURL = https://example.com XCTAssertEqual( TestRequest(baseURL: "https://example.com", path: "").absoluteURL, - NSURL(string: "https://example.com") + URL(string: "https://example.com") ) XCTAssertEqual( TestRequest(baseURL: "https://example.com", path: "/").absoluteURL, - NSURL(string: "https://example.com/") + URL(string: "https://example.com/") ) XCTAssertEqual( TestRequest(baseURL: "https://example.com", path: "/", parameters: ["p": 1]).absoluteURL, - NSURL(string: "https://example.com/?p=1") + URL(string: "https://example.com/?p=1") ) XCTAssertEqual( TestRequest(baseURL: "https://example.com", path: "foo").absoluteURL, - NSURL(string: "https://example.com/foo") + URL(string: "https://example.com/foo") ) XCTAssertEqual( TestRequest(baseURL: "https://example.com", path: "/foo", parameters: ["p": 1]).absoluteURL, - NSURL(string: "https://example.com/foo?p=1") + URL(string: "https://example.com/foo?p=1") ) XCTAssertEqual( TestRequest(baseURL: "https://example.com", path: "/foo/").absoluteURL, - NSURL(string: "https://example.com/foo/") + URL(string: "https://example.com/foo/") ) XCTAssertEqual( TestRequest(baseURL: "https://example.com", path: "/foo/", parameters: ["p": 1]).absoluteURL, - NSURL(string: "https://example.com/foo/?p=1") + URL(string: "https://example.com/foo/?p=1") ) XCTAssertEqual( TestRequest(baseURL: "https://example.com", path: "foo/bar").absoluteURL, - NSURL(string: "https://example.com/foo/bar") + URL(string: "https://example.com/foo/bar") ) XCTAssertEqual( TestRequest(baseURL: "https://example.com", path: "/foo/bar").absoluteURL, - NSURL(string: "https://example.com/foo/bar") + URL(string: "https://example.com/foo/bar") ) XCTAssertEqual( TestRequest(baseURL: "https://example.com", path: "/foo/bar", parameters: ["p": 1]).absoluteURL, - NSURL(string: "https://example.com/foo/bar?p=1") + URL(string: "https://example.com/foo/bar?p=1") ) XCTAssertEqual( TestRequest(baseURL: "https://example.com", path: "/foo/bar/").absoluteURL, - NSURL(string: "https://example.com/foo/bar/") + URL(string: "https://example.com/foo/bar/") ) XCTAssertEqual( TestRequest(baseURL: "https://example.com", path: "/foo/bar/", parameters: ["p": 1]).absoluteURL, - NSURL(string: "https://example.com/foo/bar/?p=1") + URL(string: "https://example.com/foo/bar/?p=1") ) XCTAssertEqual( TestRequest(baseURL: "https://example.com", path: "/foo/bar//").absoluteURL, - NSURL(string: "https://example.com/foo/bar//") + URL(string: "https://example.com/foo/bar//") ) // MARK: - baseURL = https://example.com/ XCTAssertEqual( TestRequest(baseURL: "https://example.com/", path: "").absoluteURL, - NSURL(string: "https://example.com/") + URL(string: "https://example.com/") ) XCTAssertEqual( TestRequest(baseURL: "https://example.com/", path: "/").absoluteURL, - NSURL(string: "https://example.com//") + URL(string: "https://example.com//") ) XCTAssertEqual( TestRequest(baseURL: "https://example.com/", path: "/", parameters: ["p": 1]).absoluteURL, - NSURL(string: "https://example.com//?p=1") + URL(string: "https://example.com//?p=1") ) XCTAssertEqual( TestRequest(baseURL: "https://example.com/", path: "foo").absoluteURL, - NSURL(string: "https://example.com/foo") + URL(string: "https://example.com/foo") ) XCTAssertEqual( TestRequest(baseURL: "https://example.com/", path: "/foo").absoluteURL, - NSURL(string: "https://example.com//foo") + URL(string: "https://example.com//foo") ) XCTAssertEqual( TestRequest(baseURL: "https://example.com/", path: "/foo", parameters: ["p": 1]).absoluteURL, - NSURL(string: "https://example.com//foo?p=1") + URL(string: "https://example.com//foo?p=1") ) XCTAssertEqual( TestRequest(baseURL: "https://example.com/", path: "/foo/").absoluteURL, - NSURL(string: "https://example.com//foo/") + URL(string: "https://example.com//foo/") ) XCTAssertEqual( TestRequest(baseURL: "https://example.com/", path: "/foo/", parameters: ["p": 1]).absoluteURL, - NSURL(string: "https://example.com//foo/?p=1") + URL(string: "https://example.com//foo/?p=1") ) XCTAssertEqual( TestRequest(baseURL: "https://example.com/", path: "foo/bar").absoluteURL, - NSURL(string: "https://example.com/foo/bar") + URL(string: "https://example.com/foo/bar") ) XCTAssertEqual( TestRequest(baseURL: "https://example.com/", path: "/foo/bar").absoluteURL, - NSURL(string: "https://example.com//foo/bar") + URL(string: "https://example.com//foo/bar") ) XCTAssertEqual( TestRequest(baseURL: "https://example.com/", path: "/foo/bar", parameters: ["p": 1]).absoluteURL, - NSURL(string: "https://example.com//foo/bar?p=1") + URL(string: "https://example.com//foo/bar?p=1") ) XCTAssertEqual( TestRequest(baseURL: "https://example.com/", path: "/foo/bar/").absoluteURL, - NSURL(string: "https://example.com//foo/bar/") + URL(string: "https://example.com//foo/bar/") ) XCTAssertEqual( TestRequest(baseURL: "https://example.com/", path: "/foo/bar/", parameters: ["p": 1]).absoluteURL, - NSURL(string: "https://example.com//foo/bar/?p=1") + URL(string: "https://example.com//foo/bar/?p=1") ) XCTAssertEqual( TestRequest(baseURL: "https://example.com/", path: "foo//bar//").absoluteURL, - NSURL(string: "https://example.com/foo//bar//") + URL(string: "https://example.com/foo//bar//") ) // MARK: - baseURL = https://example.com/api XCTAssertEqual( TestRequest(baseURL: "https://example.com/api", path: "").absoluteURL, - NSURL(string: "https://example.com/api") + URL(string: "https://example.com/api") ) XCTAssertEqual( TestRequest(baseURL: "https://example.com/api", path: "/").absoluteURL, - NSURL(string: "https://example.com/api/") + URL(string: "https://example.com/api/") ) XCTAssertEqual( TestRequest(baseURL: "https://example.com/api", path: "/", parameters: ["p": 1]).absoluteURL, - NSURL(string: "https://example.com/api/?p=1") + URL(string: "https://example.com/api/?p=1") ) XCTAssertEqual( TestRequest(baseURL: "https://example.com/api", path: "foo").absoluteURL, - NSURL(string: "https://example.com/api/foo") + URL(string: "https://example.com/api/foo") ) XCTAssertEqual( TestRequest(baseURL: "https://example.com/api", path: "/foo").absoluteURL, - NSURL(string: "https://example.com/api/foo") + URL(string: "https://example.com/api/foo") ) XCTAssertEqual( TestRequest(baseURL: "https://example.com/api", path: "/foo", parameters: ["p": 1]).absoluteURL, - NSURL(string: "https://example.com/api/foo?p=1") + URL(string: "https://example.com/api/foo?p=1") ) XCTAssertEqual( TestRequest(baseURL: "https://example.com/api", path: "/foo/").absoluteURL, - NSURL(string: "https://example.com/api/foo/") + URL(string: "https://example.com/api/foo/") ) XCTAssertEqual( TestRequest(baseURL: "https://example.com/api", path: "/foo/", parameters: ["p": 1]).absoluteURL, - NSURL(string: "https://example.com/api/foo/?p=1") + URL(string: "https://example.com/api/foo/?p=1") ) XCTAssertEqual( TestRequest(baseURL: "https://example.com/api", path: "foo/bar").absoluteURL, - NSURL(string: "https://example.com/api/foo/bar") + URL(string: "https://example.com/api/foo/bar") ) XCTAssertEqual( TestRequest(baseURL: "https://example.com/api", path: "/foo/bar").absoluteURL, - NSURL(string: "https://example.com/api/foo/bar") + URL(string: "https://example.com/api/foo/bar") ) XCTAssertEqual( TestRequest(baseURL: "https://example.com/api", path: "/foo/bar", parameters: ["p": 1]).absoluteURL, - NSURL(string: "https://example.com/api/foo/bar?p=1") + URL(string: "https://example.com/api/foo/bar?p=1") ) XCTAssertEqual( TestRequest(baseURL: "https://example.com/api", path: "/foo/bar/").absoluteURL, - NSURL(string: "https://example.com/api/foo/bar/") + URL(string: "https://example.com/api/foo/bar/") ) XCTAssertEqual( TestRequest(baseURL: "https://example.com/api", path: "/foo/bar/", parameters: ["p": 1]).absoluteURL, - NSURL(string: "https://example.com/api/foo/bar/?p=1") + URL(string: "https://example.com/api/foo/bar/?p=1") ) XCTAssertEqual( TestRequest(baseURL: "https://example.com/api", path: "foo//bar//").absoluteURL, - NSURL(string: "https://example.com/api/foo//bar//") + URL(string: "https://example.com/api/foo//bar//") ) // MARK: - baseURL = https://example.com/api/ XCTAssertEqual( TestRequest(baseURL: "https://example.com/api/", path: "").absoluteURL, - NSURL(string: "https://example.com/api/") + URL(string: "https://example.com/api/") ) XCTAssertEqual( TestRequest(baseURL: "https://example.com/api/", path: "/").absoluteURL, - NSURL(string: "https://example.com/api//") + URL(string: "https://example.com/api//") ) XCTAssertEqual( TestRequest(baseURL: "https://example.com/api/", path: "/", parameters: ["p": 1]).absoluteURL, - NSURL(string: "https://example.com/api//?p=1") + URL(string: "https://example.com/api//?p=1") ) XCTAssertEqual( TestRequest(baseURL: "https://example.com/api/", path: "foo").absoluteURL, - NSURL(string: "https://example.com/api/foo") + URL(string: "https://example.com/api/foo") ) XCTAssertEqual( TestRequest(baseURL: "https://example.com/api/", path: "/foo").absoluteURL, - NSURL(string: "https://example.com/api//foo") + URL(string: "https://example.com/api//foo") ) XCTAssertEqual( TestRequest(baseURL: "https://example.com/api/", path: "/foo", parameters: ["p": 1]).absoluteURL, - NSURL(string: "https://example.com/api//foo?p=1") + URL(string: "https://example.com/api//foo?p=1") ) XCTAssertEqual( TestRequest(baseURL: "https://example.com/api/", path: "/foo/").absoluteURL, - NSURL(string: "https://example.com/api//foo/") + URL(string: "https://example.com/api//foo/") ) XCTAssertEqual( TestRequest(baseURL: "https://example.com/api/", path: "/foo/", parameters: ["p": 1]).absoluteURL, - NSURL(string: "https://example.com/api//foo/?p=1") + URL(string: "https://example.com/api//foo/?p=1") ) XCTAssertEqual( TestRequest(baseURL: "https://example.com/api/", path: "foo/bar").absoluteURL, - NSURL(string: "https://example.com/api/foo/bar") + URL(string: "https://example.com/api/foo/bar") ) XCTAssertEqual( TestRequest(baseURL: "https://example.com/api/", path: "/foo/bar").absoluteURL, - NSURL(string: "https://example.com/api//foo/bar") + URL(string: "https://example.com/api//foo/bar") ) XCTAssertEqual( TestRequest(baseURL: "https://example.com/api/", path: "/foo/bar", parameters: ["p": 1]).absoluteURL, - NSURL(string: "https://example.com/api//foo/bar?p=1") + URL(string: "https://example.com/api//foo/bar?p=1") ) XCTAssertEqual( TestRequest(baseURL: "https://example.com/api/", path: "/foo/bar/").absoluteURL, - NSURL(string: "https://example.com/api//foo/bar/") + URL(string: "https://example.com/api//foo/bar/") ) XCTAssertEqual( TestRequest(baseURL: "https://example.com/api/", path: "/foo/bar/", parameters: ["p": 1]).absoluteURL, - NSURL(string: "https://example.com/api//foo/bar/?p=1") + URL(string: "https://example.com/api//foo/bar/?p=1") ) XCTAssertEqual( TestRequest(baseURL: "https://example.com/api/", path: "foo//bar//").absoluteURL, - NSURL(string: "https://example.com/api/foo//bar//") + URL(string: "https://example.com/api/foo//bar//") ) // MARK: - baseURL = https://example.com/// XCTAssertEqual( TestRequest(baseURL: "https://example.com///", path: "").absoluteURL, - NSURL(string: "https://example.com///") + URL(string: "https://example.com///") ) XCTAssertEqual( TestRequest(baseURL: "https://example.com///", path: "/").absoluteURL, - NSURL(string: "https://example.com////") + URL(string: "https://example.com////") ) XCTAssertEqual( TestRequest(baseURL: "https://example.com///", path: "/", parameters: ["p": 1]).absoluteURL, - NSURL(string: "https://example.com////?p=1") + URL(string: "https://example.com////?p=1") ) XCTAssertEqual( TestRequest(baseURL: "https://example.com///", path: "foo").absoluteURL, - NSURL(string: "https://example.com///foo") + URL(string: "https://example.com///foo") ) XCTAssertEqual( TestRequest(baseURL: "https://example.com///", path: "/foo").absoluteURL, - NSURL(string: "https://example.com////foo") + URL(string: "https://example.com////foo") ) XCTAssertEqual( TestRequest(baseURL: "https://example.com///", path: "/foo", parameters: ["p": 1]).absoluteURL, - NSURL(string: "https://example.com////foo?p=1") + URL(string: "https://example.com////foo?p=1") ) XCTAssertEqual( TestRequest(baseURL: "https://example.com///", path: "/foo/").absoluteURL, - NSURL(string: "https://example.com////foo/") + URL(string: "https://example.com////foo/") ) XCTAssertEqual( TestRequest(baseURL: "https://example.com///", path: "/foo/", parameters: ["p": 1]).absoluteURL, - NSURL(string: "https://example.com////foo/?p=1") + URL(string: "https://example.com////foo/?p=1") ) XCTAssertEqual( TestRequest(baseURL: "https://example.com///", path: "foo/bar").absoluteURL, - NSURL(string: "https://example.com///foo/bar") + URL(string: "https://example.com///foo/bar") ) XCTAssertEqual( TestRequest(baseURL: "https://example.com///", path: "/foo/bar").absoluteURL, - NSURL(string: "https://example.com////foo/bar") + URL(string: "https://example.com////foo/bar") ) XCTAssertEqual( TestRequest(baseURL: "https://example.com///", path: "/foo/bar", parameters: ["p": 1]).absoluteURL, - NSURL(string: "https://example.com////foo/bar?p=1") + URL(string: "https://example.com////foo/bar?p=1") ) XCTAssertEqual( TestRequest(baseURL: "https://example.com///", path: "/foo/bar/").absoluteURL, - NSURL(string: "https://example.com////foo/bar/") + URL(string: "https://example.com////foo/bar/") ) XCTAssertEqual( TestRequest(baseURL: "https://example.com///", path: "/foo/bar/", parameters: ["p": 1]).absoluteURL, - NSURL(string: "https://example.com////foo/bar/?p=1") + URL(string: "https://example.com////foo/bar/?p=1") ) XCTAssertEqual( TestRequest(baseURL: "https://example.com///", path: "foo//bar//").absoluteURL, - NSURL(string: "https://example.com///foo//bar//") + URL(string: "https://example.com///foo//bar//") ) } func testInterceptURLRequest() { - let URL = NSURL(string: "https://example.com/customize")! + let URL = Foundation.URL(string: "https://example.com/customize")! let request = TestRequest() { _ in - return NSMutableURLRequest(URL: URL) + return URLRequest(url: URL) } - XCTAssertEqual((try? request.buildURLRequest())?.URL, URL) + XCTAssertEqual((try? request.buildURLRequest())?.url, URL) } } diff --git a/Tests/APIKit/SessionAdapterType/NSURLSessionAdapterSubclassTests.swift b/Tests/APIKit/SessionAdapterType/NSURLSessionAdapterSubclassTests.swift index b01274a0..f6baa1ed 100644 --- a/Tests/APIKit/SessionAdapterType/NSURLSessionAdapterSubclassTests.swift +++ b/Tests/APIKit/SessionAdapterType/NSURLSessionAdapterSubclassTests.swift @@ -3,18 +3,18 @@ import XCTest import OHHTTPStubs import APIKit -class NSURLSessionAdapterSubclassTests: XCTestCase { - class SessionAdapter: NSURLSessionAdapter { +class URLSessionAdapterSubclassTests: XCTestCase { + class SessionAdapter: URLSessionAdapter { var functionCallFlags = [String: Bool]() - override func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError connectionError: NSError?) { + override func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { functionCallFlags[(#function)] = true - super.URLSession(session, task: task, didCompleteWithError: connectionError) + super.urlSession(session, task: task, didCompleteWithError: error) } - override func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) { + override func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) { functionCallFlags[(#function)] = true - super.URLSession(session, dataTask: dataTask, didReceiveData: data) + super.urlSession(session, dataTask: dataTask, didReceive: data) } } @@ -24,7 +24,7 @@ class NSURLSessionAdapterSubclassTests: XCTestCase { override func setUp() { super.setUp() - let configuration = NSURLSessionConfiguration.defaultSessionConfiguration() + let configuration = URLSessionConfiguration.default adapter = SessionAdapter(configuration: configuration) session = Session(adapter: adapter) } @@ -35,28 +35,28 @@ class NSURLSessionAdapterSubclassTests: XCTestCase { } func testDelegateMethodCall() { - let data = try! NSJSONSerialization.dataWithJSONObject([:], options: []) + let data = try! JSONSerialization.data(withJSONObject: [:], options: []) - OHHTTPStubs.stubRequestsPassingTest({ request in + OHHTTPStubs.stubRequests(passingTest: { request in return true }, withStubResponse: { request in return OHHTTPStubsResponse(data: data, statusCode: 200, headers: nil) }) - let expectation = expectationWithDescription("wait for response") + let expectation = self.expectation(description: "wait for response") let request = TestRequest() session.sendRequest(request) { result in - if case .Failure = result { + if case .failure = result { XCTFail() } expectation.fulfill() } - waitForExpectationsWithTimeout(10.0, handler: nil) + waitForExpectations(timeout: 10.0, handler: nil) - XCTAssertEqual(adapter.functionCallFlags["URLSession(_:task:didCompleteWithError:)"], true) - XCTAssertEqual(adapter.functionCallFlags["URLSession(_:dataTask:didReceiveData:)"], true) + XCTAssertEqual(adapter.functionCallFlags["urlSession(_:task:didCompleteWithError:)"], true) + XCTAssertEqual(adapter.functionCallFlags["urlSession(_:dataTask:didReceive:)"], true) } } diff --git a/Tests/APIKit/SessionAdapterType/NSURLSessionAdapterTests.swift b/Tests/APIKit/SessionAdapterType/NSURLSessionAdapterTests.swift index e3421f21..6e3d0c68 100644 --- a/Tests/APIKit/SessionAdapterType/NSURLSessionAdapterTests.swift +++ b/Tests/APIKit/SessionAdapterType/NSURLSessionAdapterTests.swift @@ -3,14 +3,14 @@ import APIKit import XCTest import OHHTTPStubs -class NSURLSessionAdapterTests: XCTestCase { +class URLSessionAdapterTests: XCTestCase { var session: Session! override func setUp() { super.setUp() - let configuration = NSURLSessionConfiguration.defaultSessionConfiguration() - let adapter = NSURLSessionAdapter(configuration: configuration) + let configuration = URLSessionConfiguration.default + let adapter = URLSessionAdapter(configuration: configuration) session = Session(adapter: adapter) } @@ -22,50 +22,50 @@ class NSURLSessionAdapterTests: XCTestCase { // MARK: - integration tests func testSuccess() { let dictionary = ["key": "value"] - let data = try! NSJSONSerialization.dataWithJSONObject(dictionary, options: []) + let data = try! JSONSerialization.data(withJSONObject: dictionary, options: []) - OHHTTPStubs.stubRequestsPassingTest({ request in + OHHTTPStubs.stubRequests(passingTest: { request in return true }, withStubResponse: { request in return OHHTTPStubsResponse(data: data, statusCode: 200, headers: nil) }) - let expectation = expectationWithDescription("wait for response") + let expectation = self.expectation(description: "wait for response") let request = TestRequest() session.sendRequest(request) { response in switch response { - case .Success(let dictionary): + case .success(let dictionary): XCTAssertEqual(dictionary["key"], "value") - case .Failure: + case .failure: XCTFail() } expectation.fulfill() } - waitForExpectationsWithTimeout(10.0, handler: nil) + waitForExpectations(timeout: 10.0, handler: nil) } func testConnectionError() { let error = NSError(domain: NSURLErrorDomain, code: NSURLErrorTimedOut, userInfo: nil) - OHHTTPStubs.stubRequestsPassingTest({ request in + OHHTTPStubs.stubRequests(passingTest: { request in return true }, withStubResponse: { request in return OHHTTPStubsResponse(error: error) }) - let expectation = expectationWithDescription("wait for response") + let expectation = self.expectation(description: "wait for response") let request = TestRequest() session.sendRequest(request) { response in switch response { - case .Success: + case .success: XCTFail() - case .Failure(let error): + case .failure(let error): switch error { case .ConnectionError(let error as NSError): XCTAssertEqual(error.domain, NSURLErrorDomain) @@ -78,23 +78,23 @@ class NSURLSessionAdapterTests: XCTestCase { expectation.fulfill() } - waitForExpectationsWithTimeout(10.0, handler: nil) + waitForExpectations(timeout: 10.0, handler: nil) } func testCancel() { - let data = try! NSJSONSerialization.dataWithJSONObject([:], options: []) + let data = try! JSONSerialization.data(withJSONObject: [:], options: []) - OHHTTPStubs.stubRequestsPassingTest({ request in + OHHTTPStubs.stubRequests(passingTest: { request in return true }, withStubResponse: { request in return OHHTTPStubsResponse(data: data, statusCode: 200, headers: nil).responseTime(1.0) }) - let expectation = expectationWithDescription("wait for response") + let expectation = self.expectation(description: "wait for response") let request = TestRequest() session.sendRequest(request) { result in - guard case .Failure(let error) = result, + guard case .failure(let error) = result, case .ConnectionError(let connectionError as NSError) = error else { XCTFail() return @@ -105,10 +105,10 @@ class NSURLSessionAdapterTests: XCTestCase { expectation.fulfill() } - dispatch_async(dispatch_get_main_queue()) { + DispatchQueue.main.async { self.session.cancelRequest(TestRequest.self) } - waitForExpectationsWithTimeout(10.0, handler: nil) + waitForExpectations(timeout: 10.0, handler: nil) } -} \ No newline at end of file +} diff --git a/Tests/APIKit/SessionCallbackQueueTests.swift b/Tests/APIKit/SessionCallbackQueueTests.swift index 7eb6ce31..5f219fca 100644 --- a/Tests/APIKit/SessionCallbackQueueTests.swift +++ b/Tests/APIKit/SessionCallbackQueueTests.swift @@ -11,91 +11,91 @@ class SessionCallbackQueueTests: XCTestCase { super.setUp() adapter = TestSessionAdapter() - adapter.data = try! NSJSONSerialization.dataWithJSONObject(["key": "value"], options: []) + adapter.data = try! JSONSerialization.data(withJSONObject: ["key": "value"], options: []) session = Session(adapter: adapter, callbackQueue: .Main) } func testMain() { - let expectation = expectationWithDescription("wait for response") + let expectation = self.expectation(description: "wait for response") let request = TestRequest() session.sendRequest(request, callbackQueue: .Main) { result in - XCTAssert(NSThread.isMainThread()) + XCTAssert(Thread.isMainThread) expectation.fulfill() } - waitForExpectationsWithTimeout(1.0, handler: nil) + waitForExpectations(timeout: 1.0, handler: nil) } func testSessionQueue() { - let expectation = expectationWithDescription("wait for response") + let expectation = self.expectation(description: "wait for response") let request = TestRequest() session.sendRequest(request, callbackQueue: .SessionQueue) { result in // This depends on implementation of TestSessionAdapter - XCTAssert(NSThread.isMainThread()) + XCTAssert(Thread.isMainThread) expectation.fulfill() } - waitForExpectationsWithTimeout(1.0, handler: nil) + waitForExpectations(timeout: 1.0, handler: nil) } func testOperationQueue() { - let operationQueue = NSOperationQueue() - let expectation = expectationWithDescription("wait for response") + let operationQueue = OperationQueue() + let expectation = self.expectation(description: "wait for response") let request = TestRequest() session.sendRequest(request, callbackQueue: .OperationQueue(operationQueue)) { result in - XCTAssertEqual(NSOperationQueue.currentQueue(), operationQueue) + XCTAssertEqual(OperationQueue.current, operationQueue) expectation.fulfill() } - waitForExpectationsWithTimeout(1.0, handler: nil) + waitForExpectations(timeout: 1.0, handler: nil) } func testDispatchQueue() { - let dispatchQueue = dispatch_get_global_queue(QOS_CLASS_DEFAULT, 0) - let expectation = expectationWithDescription("wait for response") + let dispatchQueue = DispatchQueue.global(qos: .default) + let expectation = self.expectation(description: "wait for response") let request = TestRequest() session.sendRequest(request, callbackQueue: .DispatchQueue(dispatchQueue)) { result in // There is no way to test current dispatch queue. - XCTAssert(!NSThread.isMainThread()) + XCTAssert(!Thread.isMainThread) expectation.fulfill() } - waitForExpectationsWithTimeout(1.0, handler: nil) + waitForExpectations(timeout: 1.0, handler: nil) } // MARK: Test Session.callbackQueue func testImplicitSessionCallbackQueue() { - let operationQueue = NSOperationQueue() + let operationQueue = OperationQueue() let session = Session(adapter: adapter, callbackQueue: .OperationQueue(operationQueue)) - let expectation = expectationWithDescription("wait for response") + let expectation = self.expectation(description: "wait for response") let request = TestRequest() session.sendRequest(request) { result in - XCTAssertEqual(NSOperationQueue.currentQueue(), operationQueue) + XCTAssertEqual(OperationQueue.current, operationQueue) expectation.fulfill() } - waitForExpectationsWithTimeout(1.0, handler: nil) + waitForExpectations(timeout: 1.0, handler: nil) } func testExplicitSessionCallbackQueue() { - let operationQueue = NSOperationQueue() + let operationQueue = OperationQueue() let session = Session(adapter: adapter, callbackQueue: .OperationQueue(operationQueue)) - let expectation = expectationWithDescription("wait for response") + let expectation = self.expectation(description: "wait for response") let request = TestRequest() session.sendRequest(request, callbackQueue: nil) { result in - XCTAssertEqual(NSOperationQueue.currentQueue(), operationQueue) + XCTAssertEqual(OperationQueue.current, operationQueue) expectation.fulfill() } - waitForExpectationsWithTimeout(1.0, handler: nil) + waitForExpectations(timeout: 1.0, handler: nil) } } diff --git a/Tests/APIKit/SessionTests.swift b/Tests/APIKit/SessionTests.swift index e6af1e38..f0fe5076 100644 --- a/Tests/APIKit/SessionTests.swift +++ b/Tests/APIKit/SessionTests.swift @@ -17,35 +17,35 @@ class SessionTests: XCTestCase { func testSuccess() { let dictionary = ["key": "value"] - adapter.data = try! NSJSONSerialization.dataWithJSONObject(dictionary, options: []) + adapter.data = try! JSONSerialization.data(withJSONObject: dictionary, options: []) - let expectation = expectationWithDescription("wait for response") + let expectation = self.expectation(description: "wait for response") let request = TestRequest() session.sendRequest(request) { response in switch response { - case .Success(let dictionary): + case .success(let dictionary): XCTAssertEqual(dictionary["key"], "value") - case .Failure: + case .failure: XCTFail() } expectation.fulfill() } - waitForExpectationsWithTimeout(1.0, handler: nil) + waitForExpectations(timeout: 1.0, handler: nil) } // MARK: Response error func testParseDataError() { - adapter.data = "{\"broken\": \"json}".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) + adapter.data = "{\"broken\": \"json}".data(using: .utf8, allowLossyConversion: false) - let expectation = expectationWithDescription("wait for response") + let expectation = self.expectation(description: "wait for response") let request = TestRequest() session.sendRequest(request) { result in - if case .Failure(let error) = result, + if case .failure(let error) = result, case .ResponseError(let responseError as NSError) = error { XCTAssertEqual(responseError.domain, NSCocoaErrorDomain) XCTAssertEqual(responseError.code, 3840) @@ -56,17 +56,17 @@ class SessionTests: XCTestCase { expectation.fulfill() } - waitForExpectationsWithTimeout(1.0, handler: nil) + waitForExpectations(timeout: 1.0, handler: nil) } func testUnacceptableStatusCodeError() { - adapter.URLResponse = NSHTTPURLResponse(URL: NSURL(), statusCode: 400, HTTPVersion: nil, headerFields: nil) + adapter.URLResponse = HTTPURLResponse(url: NSURL(string: "")! as URL, statusCode: 400, httpVersion: nil, headerFields: nil) - let expectation = expectationWithDescription("wait for response") + let expectation = self.expectation(description: "wait for response") let request = TestRequest() session.sendRequest(request) { result in - if case .Failure(let error) = result, + if case .failure(let error) = result, case .ResponseError(let responseError as ResponseError) = error, case .UnacceptableStatusCode(let statusCode) = responseError { XCTAssertEqual(statusCode, 400) @@ -77,17 +77,17 @@ class SessionTests: XCTestCase { expectation.fulfill() } - waitForExpectationsWithTimeout(1.0, handler: nil) + waitForExpectations(timeout: 1.0, handler: nil) } func testNonHTTPURLResponseError() { - adapter.URLResponse = NSURLResponse() + adapter.URLResponse = URLResponse() - let expectation = expectationWithDescription("wait for response") + let expectation = self.expectation(description: "wait for response") let request = TestRequest() session.sendRequest(request) { result in - if case .Failure(let error) = result, + if case .failure(let error) = result, case .ResponseError(let responseError as ResponseError) = error, case .NonHTTPURLResponse(let URLResponse) = responseError { XCTAssert(URLResponse === self.adapter.URLResponse) @@ -98,20 +98,20 @@ class SessionTests: XCTestCase { expectation.fulfill() } - waitForExpectationsWithTimeout(1.0, handler: nil) + waitForExpectations(timeout: 1.0, handler: nil) } // MARK: Request error func testRequestError() { - struct Error: ErrorType {} + struct Error: Swift.Error {} - let expectation = expectationWithDescription("wait for response") - let request = TestRequest() { URLRequest in + let expectation = self.expectation(description: "wait for response") + let request = TestRequest() { urlRequest in throw Error() } session.sendRequest(request) { result in - if case .Failure(let error) = result, + if case .failure(let error) = result, case .RequestError(let requestError) = error { XCTAssert(requestError is Error) } else { @@ -121,17 +121,17 @@ class SessionTests: XCTestCase { expectation.fulfill() } - waitForExpectationsWithTimeout(1.0, handler: nil) + waitForExpectations(timeout: 1.0, handler: nil) } // MARK: Cancel func testCancel() { - let expectation = expectationWithDescription("wait for response") + let expectation = self.expectation(description: "wait for response") let request = TestRequest() session.sendRequest(request) { result in - if case .Failure(let error) = result, + if case .failure(let error) = result, case .ConnectionError(let connectionError as NSError) = error { XCTAssertEqual(connectionError.code, 0) } else { @@ -143,26 +143,26 @@ class SessionTests: XCTestCase { session.cancelRequest(TestRequest.self) - waitForExpectationsWithTimeout(1.0, handler: nil) + waitForExpectations(timeout: 1.0, handler: nil) } func testCancelFilter() { - let successExpectation = expectationWithDescription("wait for response") + let successExpectation = expectation(description: "wait for response") let successRequest = TestRequest(path: "/success") session.sendRequest(successRequest) { result in - if case .Failure = result { + if case .failure = result { XCTFail() } successExpectation.fulfill() } - let failureExpectation = expectationWithDescription("wait for response") + let failureExpectation = expectation(description: "wait for response") let failureRequest = TestRequest(path: "/failure") session.sendRequest(failureRequest) { result in - if case .Success = result { + if case .success = result { XCTFail() } @@ -173,14 +173,14 @@ class SessionTests: XCTestCase { return request.path == failureRequest.path } - waitForExpectationsWithTimeout(1.0, handler: nil) + waitForExpectations(timeout: 1.0, handler: nil) } struct AnotherTestRequest: RequestType { typealias Response = Void - var baseURL: NSURL { - return NSURL(string: "https://example.com")! + var baseURL: URL { + return URL(string: "https://example.com")! } var method: HTTPMethod { @@ -191,28 +191,28 @@ class SessionTests: XCTestCase { return "/" } - func responseFromObject(object: AnyObject, URLResponse: NSHTTPURLResponse) throws -> Response { + func responseFromObject(_ object: AnyObject, urlResponse: HTTPURLResponse) throws -> Response { return () } } func testCancelOtherRequestType() { - let successExpectation = expectationWithDescription("wait for response") + let successExpectation = expectation(description: "wait for response") let successRequest = AnotherTestRequest() session.sendRequest(successRequest) { result in - if case .Failure = result { + if case .failure = result { XCTFail() } successExpectation.fulfill() } - let failureExpectation = expectationWithDescription("wait for response") + let failureExpectation = expectation(description: "wait for response") let failureRequest = TestRequest() session.sendRequest(failureRequest) { result in - if case .Success = result { + if case .success = result { XCTFail() } @@ -221,7 +221,7 @@ class SessionTests: XCTestCase { session.cancelRequest(TestRequest.self) - waitForExpectationsWithTimeout(1.0, handler: nil) + waitForExpectations(timeout: 1.0, handler: nil) } // MARK: Class methods @@ -239,12 +239,12 @@ class SessionTests: XCTestCase { return testSesssion } - private override func sendRequest(request: Request, callbackQueue: CallbackQueue?, handler: (Result) -> Void) -> SessionTaskType? { + private override func sendRequest(_ request: Request, callbackQueue: CallbackQueue?, handler: (Result) -> Void) -> SessionTaskType? { functionCallFlags[(#function)] = true return super.sendRequest(request) } - private override func cancelRequest(requestType: Request.Type, passingTest test: Request -> Bool) { + private override func cancelRequest(_ requestType: Request.Type, passingTest test: (Request) -> Bool) { functionCallFlags[(#function)] = true } } diff --git a/Tests/APIKit/TestComponents/TestRequest.swift b/Tests/APIKit/TestComponents/TestRequest.swift index 45c63fd6..eeca4a01 100644 --- a/Tests/APIKit/TestComponents/TestRequest.swift +++ b/Tests/APIKit/TestComponents/TestRequest.swift @@ -2,16 +2,16 @@ import Foundation import APIKit struct TestRequest: RequestType { - var absoluteURL: NSURL? { - let URLRequest = try? buildURLRequest() - return URLRequest?.URL + var absoluteURL: URL? { + let urlRequest = try? buildURLRequest() + return urlRequest?.url } // MARK: RequestType typealias Response = AnyObject - init(baseURL: String = "https://example.com", path: String = "/", method: HTTPMethod = .GET, parameters: AnyObject? = [:], headerFields: [String: String] = [:], interceptURLRequest: NSMutableURLRequest throws -> NSMutableURLRequest = { $0 }) { - self.baseURL = NSURL(string: baseURL)! + init(baseURL: String = "https://example.com", path: String = "/", method: HTTPMethod = .GET, parameters: AnyObject? = [:], headerFields: [String: String] = [:], interceptURLRequest: (URLRequest) throws -> URLRequest = { $0 }) { + self.baseURL = URL(string: baseURL)! self.path = path self.method = method self.parameters = parameters @@ -19,18 +19,18 @@ struct TestRequest: RequestType { self.interceptURLRequest = interceptURLRequest } - let baseURL: NSURL + let baseURL: URL let method: HTTPMethod let path: String let parameters: AnyObject? let headerFields: [String: String] - let interceptURLRequest: NSMutableURLRequest throws -> NSMutableURLRequest + let interceptURLRequest: (URLRequest) throws -> URLRequest - func interceptURLRequest(_ URLRequest: NSMutableURLRequest) throws -> NSMutableURLRequest { - return try interceptURLRequest(URLRequest) + func interceptURLRequest(_ urlRequest: URLRequest) throws -> URLRequest { + return try interceptURLRequest(urlRequest) } - func responseFromObject(object: AnyObject, URLResponse: NSHTTPURLResponse) throws -> Response { + func responseFromObject(_ object: AnyObject, urlResponse: HTTPURLResponse) throws -> Response { return object } } diff --git a/Tests/APIKit/TestComponents/TestSessionAdapter.swift b/Tests/APIKit/TestComponents/TestSessionAdapter.swift index 76b7b1c6..a0e3c939 100644 --- a/Tests/APIKit/TestComponents/TestSessionAdapter.swift +++ b/Tests/APIKit/TestComponents/TestSessionAdapter.swift @@ -2,13 +2,13 @@ import Foundation import APIKit class TestSessionAdapter: SessionAdapterType { - enum Error: ErrorType { - case Cancelled + enum Error: Swift.Error { + case cancelled } - var data: NSData? - var URLResponse: NSURLResponse? - var error: ErrorType? + var data: Data? + var URLResponse: URLResponse? + var error: Error? private class Runner { weak var adapter: TestSessionAdapter? @@ -20,15 +20,15 @@ class TestSessionAdapter: SessionAdapterType { private var tasks = [TestSessionTask]() private let runner: Runner - private let timer: NSTimer + private let timer: Timer - init(data: NSData? = NSData(), URLResponse: NSURLResponse? = NSHTTPURLResponse(URL: NSURL(), statusCode: 200, HTTPVersion: nil, headerFields: nil), error: NSError? = nil) { + init(data: Data? = Data(), URLResponse: URLResponse? = HTTPURLResponse(url: NSURL(string: "")! as URL, statusCode: 200, httpVersion: nil, headerFields: nil), error: Error? = nil) { self.data = data self.URLResponse = URLResponse self.error = error self.runner = Runner() - self.timer = NSTimer.scheduledTimerWithTimeInterval(0.001, + self.timer = Timer.scheduledTimer(timeInterval: 0.001, target: runner, selector: #selector(Runner.run), userInfo: nil, @@ -40,7 +40,7 @@ class TestSessionAdapter: SessionAdapterType { func executeAllTasks() { for task in tasks { if task.cancelled { - task.handler(nil, nil, Error.Cancelled) + task.handler(nil, nil, Error.cancelled) } else { task.handler(data, URLResponse, error) } @@ -49,14 +49,14 @@ class TestSessionAdapter: SessionAdapterType { tasks = [] } - func createTaskWithURLRequest(URLRequest: NSURLRequest, handler: (NSData?, NSURLResponse?, ErrorType?) -> Void) -> SessionTaskType { + func createTaskWithURLRequest(_ URLRequest: URLRequest, handler: (NSData?, URLResponse?, Swift.Error?) -> Void) -> SessionTaskType { let task = TestSessionTask(handler: handler) tasks.append(task) return task } - func getTasksWithHandler(handler: [SessionTaskType] -> Void) { + func getTasksWithHandler(_ handler: ([SessionTaskType]) -> Void) { handler(tasks.map { $0 }) } } diff --git a/Tests/APIKit/TestComponents/TestSessionTask.swift b/Tests/APIKit/TestComponents/TestSessionTask.swift index 15bf3add..abbdbea1 100644 --- a/Tests/APIKit/TestComponents/TestSessionTask.swift +++ b/Tests/APIKit/TestComponents/TestSessionTask.swift @@ -3,10 +3,10 @@ import APIKit class TestSessionTask: SessionTaskType { - var handler: (NSData?, NSURLResponse?, ErrorType?) -> Void + var handler: (NSData?, URLResponse?, Error?) -> Void var cancelled = false - init(handler: (NSData?, NSURLResponse?, ErrorType?) -> Void) { + init(handler: (NSData?, URLResponse?, Error?) -> Void) { self.handler = handler } From 9cf0b19531340c461c4a0b579d82e7892d5f319f Mon Sep 17 00:00:00 2001 From: Syo Ikeda Date: Mon, 8 Aug 2016 22:38:14 +0900 Subject: [PATCH 04/38] Update OHHTTPStubs --- .gitmodules | 2 +- Cartfile.private | 2 +- Cartfile.resolved | 2 +- Carthage/Checkouts/OHHTTPStubs | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/.gitmodules b/.gitmodules index 30480090..fc535505 100644 --- a/.gitmodules +++ b/.gitmodules @@ -3,4 +3,4 @@ url = https://github.com/antitypical/Result.git [submodule "Carthage/Checkouts/OHHTTPStubs"] path = Carthage/Checkouts/OHHTTPStubs - url = https://github.com/AliSoftware/OHHTTPStubs.git + url = https://github.com/ikesyo/OHHTTPStubs.git diff --git a/Cartfile.private b/Cartfile.private index 7f203a08..95495240 100644 --- a/Cartfile.private +++ b/Cartfile.private @@ -1 +1 @@ -github "AliSoftware/OHHTTPStubs" "4995ecd" +github "ikesyo/OHHTTPStubs" "swift3" diff --git a/Cartfile.resolved b/Cartfile.resolved index 19067c74..da6b78b8 100644 --- a/Cartfile.resolved +++ b/Cartfile.resolved @@ -1,2 +1,2 @@ -github "AliSoftware/OHHTTPStubs" "4995ecd762abdd81227d14faf65fde003fbbe789" +github "ikesyo/OHHTTPStubs" "a2e8edf5fc75adc80bd17743a07b262d3f3063b3" github "antitypical/Result" "3.0.0-alpha.2" diff --git a/Carthage/Checkouts/OHHTTPStubs b/Carthage/Checkouts/OHHTTPStubs index 4995ecd7..a2e8edf5 160000 --- a/Carthage/Checkouts/OHHTTPStubs +++ b/Carthage/Checkouts/OHHTTPStubs @@ -1 +1 @@ -Subproject commit 4995ecd762abdd81227d14faf65fde003fbbe789 +Subproject commit a2e8edf5fc75adc80bd17743a07b262d3f3063b3 From d94fbc90fd7f8e6531540d1488722a1ac9a7a60d Mon Sep 17 00:00:00 2001 From: Syo Ikeda Date: Mon, 8 Aug 2016 22:43:18 +0900 Subject: [PATCH 05/38] Update Playground --- Demo.playground/Contents.swift | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/Demo.playground/Contents.swift b/Demo.playground/Contents.swift index 8c15d89a..3279d6a4 100644 --- a/Demo.playground/Contents.swift +++ b/Demo.playground/Contents.swift @@ -1,8 +1,8 @@ -import XCPlayground +import PlaygroundSupport import UIKit import APIKit -XCPlaygroundPage.currentPage.needsIndefiniteExecution = true +PlaygroundPage.current.needsIndefiniteExecution = true //: Step 1: Define request protocol protocol GitHubRequestType: RequestType { @@ -10,27 +10,27 @@ protocol GitHubRequestType: RequestType { } extension GitHubRequestType { - var baseURL: NSURL { - return NSURL(string: "https://api.github.com")! + var baseURL: URL { + return URL(string: "https://api.github.com")! } } //: Step 2: Create model object struct RateLimit { let count: Int - let resetDate: NSDate + let resetDate: Date init?(dictionary: [String: AnyObject]) { guard let count = dictionary["rate"]?["limit"] as? Int else { return nil } - guard let resetDateString = dictionary["rate"]?["reset"] as? NSTimeInterval else { + guard let resetDateString = dictionary["rate"]?["reset"] as? TimeInterval else { return nil } self.count = count - self.resetDate = NSDate(timeIntervalSince1970: resetDateString) + self.resetDate = Date(timeIntervalSince1970: resetDateString) } } @@ -47,7 +47,7 @@ struct GetRateLimitRequest: GitHubRequestType { return "/rate_limit" } - func responseFromObject(object: AnyObject, URLResponse: NSHTTPURLResponse) throws -> Response { + func responseFromObject(_ object: AnyObject, urlResponse: HTTPURLResponse) throws -> Response { guard let dictionary = object as? [String: AnyObject], let rateLimit = RateLimit(dictionary: dictionary) else { throw ResponseError.UnexpectedObject(object) From a0e5cb75003aaa8b3926fcb01282d3e463babbfb Mon Sep 17 00:00:00 2001 From: Syo Ikeda Date: Mon, 8 Aug 2016 22:46:04 +0900 Subject: [PATCH 06/38] Update .travis.yml --- .travis.yml | 4 ---- 1 file changed, 4 deletions(-) diff --git a/.travis.yml b/.travis.yml index 12df949e..d3759ecd 100644 --- a/.travis.yml +++ b/.travis.yml @@ -5,10 +5,6 @@ env: matrix: include: - - os: osx - language: objective-c - osx_image: xcode7.3 - env: JOB=Xcode7.3 - os: osx language: objective-c osx_image: xcode8 From 4fb7d36a9c598537df522207bb990d7f7724e569 Mon Sep 17 00:00:00 2001 From: Syo Ikeda Date: Mon, 8 Aug 2016 22:53:42 +0900 Subject: [PATCH 07/38] [MultipartFormDataBodyParameters.Part] Rename length to count --- .../MultipartFormDataBodyParameters.swift | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/Sources/BodyParametersType/MultipartFormDataBodyParameters.swift b/Sources/BodyParametersType/MultipartFormDataBodyParameters.swift index b13d0b54..ff643d22 100644 --- a/Sources/BodyParametersType/MultipartFormDataBodyParameters.swift +++ b/Sources/BodyParametersType/MultipartFormDataBodyParameters.swift @@ -61,7 +61,7 @@ public extension MultipartFormDataBodyParameters { public let name: String public let mimeType: String? public let fileName: String? - public let length: Int + public let count: Int /// Returns Part instance that has data presentation of passed value. /// `value` will be converted via `String(_:)` and serialized via `String.dataUsingEncoding(_:)`. @@ -75,7 +75,7 @@ public extension MultipartFormDataBodyParameters { self.name = name self.mimeType = mimeType self.fileName = fileName - self.length = data.count + self.count = data.count } /// Returns Part instance that has input stream of specifed data. @@ -85,7 +85,7 @@ public extension MultipartFormDataBodyParameters { self.name = name self.mimeType = mimeType self.fileName = fileName - self.length = data.count + self.count = data.count } /// Returns Part instance that has input stream of specifed file URL. @@ -112,7 +112,7 @@ public extension MultipartFormDataBodyParameters { self.name = name self.mimeType = mimeType ?? detectedMimeType ?? "application/octet-stream" self.fileName = fileName ?? fileURL.lastPathComponent - self.length = bodyLength + self.count = bodyLength } } @@ -140,7 +140,7 @@ public extension MultipartFormDataBodyParameters { headerData = header.data(using: .utf8)! footerData = "\r\n".data(using: .utf8)! bodyPart = part - totalLength = headerData.count + bodyPart.length + footerData.count + totalLength = headerData.count + bodyPart.count + footerData.count totalSentLength = 0 super.init() @@ -151,7 +151,7 @@ public extension MultipartFormDataBodyParameters { } var bodyRange: Range { - return headerRange.upperBound..<(headerRange.upperBound + bodyPart.length) + return headerRange.upperBound..<(headerRange.upperBound + bodyPart.count) } var footerRange: Range { From da1182d99f4a0e096ee451d95814f90ac1c20814 Mon Sep 17 00:00:00 2001 From: Syo Ikeda Date: Mon, 8 Aug 2016 22:54:39 +0900 Subject: [PATCH 08/38] Rename fileURL to fileUrl --- .../MultipartFormDataBodyParameters.swift | 14 +++++++------- .../MultipartFormDataParametersTests.swift | 6 +++--- 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/Sources/BodyParametersType/MultipartFormDataBodyParameters.swift b/Sources/BodyParametersType/MultipartFormDataBodyParameters.swift index ff643d22..f8541cbd 100644 --- a/Sources/BodyParametersType/MultipartFormDataBodyParameters.swift +++ b/Sources/BodyParametersType/MultipartFormDataBodyParameters.swift @@ -90,20 +90,20 @@ public extension MultipartFormDataBodyParameters { /// Returns Part instance that has input stream of specifed file URL. /// If `mimeType` or `fileName` are `nil`, values for the fields will be detected from URL. - public init(fileURL: URL, name: String, mimeType: String? = nil, fileName: String? = nil) throws { - guard let inputStream = InputStream(url: fileURL) else { - throw Error.IllegalFileURL(fileURL) + public init(fileUrl: URL, name: String, mimeType: String? = nil, fileName: String? = nil) throws { + guard let inputStream = InputStream(url: fileUrl) else { + throw Error.IllegalFileURL(fileUrl) } - let fileSize = (try? FileManager.default.attributesOfItem(atPath: fileURL.path)) + let fileSize = (try? FileManager.default.attributesOfItem(atPath: fileUrl.path)) .flatMap { $0[FileAttributeKey.size] as? NSNumber } .map { $0.intValue } guard let bodyLength = fileSize else { - throw Error.CannotGetFileSize(fileURL) + throw Error.CannotGetFileSize(fileUrl) } - let detectedMimeType = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, fileURL.pathExtension, nil) + let detectedMimeType = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, fileUrl.pathExtension, nil) .map { $0.takeRetainedValue() } .flatMap { UTTypeCopyPreferredTagWithClass($0, kUTTagClassMIMEType)?.takeRetainedValue() } .map { $0 as String } @@ -111,7 +111,7 @@ public extension MultipartFormDataBodyParameters { self.inputStream = inputStream self.name = name self.mimeType = mimeType ?? detectedMimeType ?? "application/octet-stream" - self.fileName = fileName ?? fileURL.lastPathComponent + self.fileName = fileName ?? fileUrl.lastPathComponent self.count = bodyLength } } diff --git a/Tests/APIKit/BodyParametersType/MultipartFormDataParametersTests.swift b/Tests/APIKit/BodyParametersType/MultipartFormDataParametersTests.swift index 21ff54dc..94f61a22 100644 --- a/Tests/APIKit/BodyParametersType/MultipartFormDataParametersTests.swift +++ b/Tests/APIKit/BodyParametersType/MultipartFormDataParametersTests.swift @@ -71,8 +71,8 @@ class MultipartFormDataParametersTests: XCTestCase { // MARK: Values func testFileValue() { - let fileURL = Bundle(for: self.dynamicType).url(forResource: "test", withExtension: "json")! - let part = try! MultipartFormDataBodyParameters.Part(fileURL: fileURL, name: "test") + let fileUrl = Bundle(for: self.dynamicType).url(forResource: "test", withExtension: "json")! + let part = try! MultipartFormDataBodyParameters.Part(fileUrl: fileUrl, name: "test") let parameters = MultipartFormDataBodyParameters(parts: [part]) do { @@ -81,7 +81,7 @@ class MultipartFormDataParametersTests: XCTestCase { return } - let testData = try! Data(contentsOf: fileURL) + let testData = try! Data(contentsOf: fileUrl) let testString = String(data: testData, encoding: .utf8)! let encodedData = String(data: data, encoding:.utf8)! From b041b71f7f14be1507743b37548417efdbde5a62 Mon Sep 17 00:00:00 2001 From: Syo Ikeda Date: Mon, 8 Aug 2016 22:56:47 +0900 Subject: [PATCH 09/38] Rename absoluteURL to absoluteUrl --- Tests/APIKit/RequestTypeTests.swift | 138 +++++++++--------- Tests/APIKit/TestComponents/TestRequest.swift | 2 +- 2 files changed, 70 insertions(+), 70 deletions(-) diff --git a/Tests/APIKit/RequestTypeTests.swift b/Tests/APIKit/RequestTypeTests.swift index 2dfb56b7..9a26c6ae 100644 --- a/Tests/APIKit/RequestTypeTests.swift +++ b/Tests/APIKit/RequestTypeTests.swift @@ -60,351 +60,351 @@ class RequestTypeTests: XCTestCase { func testBuildURL() { // MARK: - baseURL = https://example.com XCTAssertEqual( - TestRequest(baseURL: "https://example.com", path: "").absoluteURL, + TestRequest(baseURL: "https://example.com", path: "").absoluteUrl, URL(string: "https://example.com") ) XCTAssertEqual( - TestRequest(baseURL: "https://example.com", path: "/").absoluteURL, + TestRequest(baseURL: "https://example.com", path: "/").absoluteUrl, URL(string: "https://example.com/") ) XCTAssertEqual( - TestRequest(baseURL: "https://example.com", path: "/", parameters: ["p": 1]).absoluteURL, + TestRequest(baseURL: "https://example.com", path: "/", parameters: ["p": 1]).absoluteUrl, URL(string: "https://example.com/?p=1") ) XCTAssertEqual( - TestRequest(baseURL: "https://example.com", path: "foo").absoluteURL, + TestRequest(baseURL: "https://example.com", path: "foo").absoluteUrl, URL(string: "https://example.com/foo") ) XCTAssertEqual( - TestRequest(baseURL: "https://example.com", path: "/foo", parameters: ["p": 1]).absoluteURL, + TestRequest(baseURL: "https://example.com", path: "/foo", parameters: ["p": 1]).absoluteUrl, URL(string: "https://example.com/foo?p=1") ) XCTAssertEqual( - TestRequest(baseURL: "https://example.com", path: "/foo/").absoluteURL, + TestRequest(baseURL: "https://example.com", path: "/foo/").absoluteUrl, URL(string: "https://example.com/foo/") ) XCTAssertEqual( - TestRequest(baseURL: "https://example.com", path: "/foo/", parameters: ["p": 1]).absoluteURL, + TestRequest(baseURL: "https://example.com", path: "/foo/", parameters: ["p": 1]).absoluteUrl, URL(string: "https://example.com/foo/?p=1") ) XCTAssertEqual( - TestRequest(baseURL: "https://example.com", path: "foo/bar").absoluteURL, + TestRequest(baseURL: "https://example.com", path: "foo/bar").absoluteUrl, URL(string: "https://example.com/foo/bar") ) XCTAssertEqual( - TestRequest(baseURL: "https://example.com", path: "/foo/bar").absoluteURL, + TestRequest(baseURL: "https://example.com", path: "/foo/bar").absoluteUrl, URL(string: "https://example.com/foo/bar") ) XCTAssertEqual( - TestRequest(baseURL: "https://example.com", path: "/foo/bar", parameters: ["p": 1]).absoluteURL, + TestRequest(baseURL: "https://example.com", path: "/foo/bar", parameters: ["p": 1]).absoluteUrl, URL(string: "https://example.com/foo/bar?p=1") ) XCTAssertEqual( - TestRequest(baseURL: "https://example.com", path: "/foo/bar/").absoluteURL, + TestRequest(baseURL: "https://example.com", path: "/foo/bar/").absoluteUrl, URL(string: "https://example.com/foo/bar/") ) XCTAssertEqual( - TestRequest(baseURL: "https://example.com", path: "/foo/bar/", parameters: ["p": 1]).absoluteURL, + TestRequest(baseURL: "https://example.com", path: "/foo/bar/", parameters: ["p": 1]).absoluteUrl, URL(string: "https://example.com/foo/bar/?p=1") ) XCTAssertEqual( - TestRequest(baseURL: "https://example.com", path: "/foo/bar//").absoluteURL, + TestRequest(baseURL: "https://example.com", path: "/foo/bar//").absoluteUrl, URL(string: "https://example.com/foo/bar//") ) // MARK: - baseURL = https://example.com/ XCTAssertEqual( - TestRequest(baseURL: "https://example.com/", path: "").absoluteURL, + TestRequest(baseURL: "https://example.com/", path: "").absoluteUrl, URL(string: "https://example.com/") ) XCTAssertEqual( - TestRequest(baseURL: "https://example.com/", path: "/").absoluteURL, + TestRequest(baseURL: "https://example.com/", path: "/").absoluteUrl, URL(string: "https://example.com//") ) XCTAssertEqual( - TestRequest(baseURL: "https://example.com/", path: "/", parameters: ["p": 1]).absoluteURL, + TestRequest(baseURL: "https://example.com/", path: "/", parameters: ["p": 1]).absoluteUrl, URL(string: "https://example.com//?p=1") ) XCTAssertEqual( - TestRequest(baseURL: "https://example.com/", path: "foo").absoluteURL, + TestRequest(baseURL: "https://example.com/", path: "foo").absoluteUrl, URL(string: "https://example.com/foo") ) XCTAssertEqual( - TestRequest(baseURL: "https://example.com/", path: "/foo").absoluteURL, + TestRequest(baseURL: "https://example.com/", path: "/foo").absoluteUrl, URL(string: "https://example.com//foo") ) XCTAssertEqual( - TestRequest(baseURL: "https://example.com/", path: "/foo", parameters: ["p": 1]).absoluteURL, + TestRequest(baseURL: "https://example.com/", path: "/foo", parameters: ["p": 1]).absoluteUrl, URL(string: "https://example.com//foo?p=1") ) XCTAssertEqual( - TestRequest(baseURL: "https://example.com/", path: "/foo/").absoluteURL, + TestRequest(baseURL: "https://example.com/", path: "/foo/").absoluteUrl, URL(string: "https://example.com//foo/") ) XCTAssertEqual( - TestRequest(baseURL: "https://example.com/", path: "/foo/", parameters: ["p": 1]).absoluteURL, + TestRequest(baseURL: "https://example.com/", path: "/foo/", parameters: ["p": 1]).absoluteUrl, URL(string: "https://example.com//foo/?p=1") ) XCTAssertEqual( - TestRequest(baseURL: "https://example.com/", path: "foo/bar").absoluteURL, + TestRequest(baseURL: "https://example.com/", path: "foo/bar").absoluteUrl, URL(string: "https://example.com/foo/bar") ) XCTAssertEqual( - TestRequest(baseURL: "https://example.com/", path: "/foo/bar").absoluteURL, + TestRequest(baseURL: "https://example.com/", path: "/foo/bar").absoluteUrl, URL(string: "https://example.com//foo/bar") ) XCTAssertEqual( - TestRequest(baseURL: "https://example.com/", path: "/foo/bar", parameters: ["p": 1]).absoluteURL, + TestRequest(baseURL: "https://example.com/", path: "/foo/bar", parameters: ["p": 1]).absoluteUrl, URL(string: "https://example.com//foo/bar?p=1") ) XCTAssertEqual( - TestRequest(baseURL: "https://example.com/", path: "/foo/bar/").absoluteURL, + TestRequest(baseURL: "https://example.com/", path: "/foo/bar/").absoluteUrl, URL(string: "https://example.com//foo/bar/") ) XCTAssertEqual( - TestRequest(baseURL: "https://example.com/", path: "/foo/bar/", parameters: ["p": 1]).absoluteURL, + TestRequest(baseURL: "https://example.com/", path: "/foo/bar/", parameters: ["p": 1]).absoluteUrl, URL(string: "https://example.com//foo/bar/?p=1") ) XCTAssertEqual( - TestRequest(baseURL: "https://example.com/", path: "foo//bar//").absoluteURL, + TestRequest(baseURL: "https://example.com/", path: "foo//bar//").absoluteUrl, URL(string: "https://example.com/foo//bar//") ) // MARK: - baseURL = https://example.com/api XCTAssertEqual( - TestRequest(baseURL: "https://example.com/api", path: "").absoluteURL, + TestRequest(baseURL: "https://example.com/api", path: "").absoluteUrl, URL(string: "https://example.com/api") ) XCTAssertEqual( - TestRequest(baseURL: "https://example.com/api", path: "/").absoluteURL, + TestRequest(baseURL: "https://example.com/api", path: "/").absoluteUrl, URL(string: "https://example.com/api/") ) XCTAssertEqual( - TestRequest(baseURL: "https://example.com/api", path: "/", parameters: ["p": 1]).absoluteURL, + TestRequest(baseURL: "https://example.com/api", path: "/", parameters: ["p": 1]).absoluteUrl, URL(string: "https://example.com/api/?p=1") ) XCTAssertEqual( - TestRequest(baseURL: "https://example.com/api", path: "foo").absoluteURL, + TestRequest(baseURL: "https://example.com/api", path: "foo").absoluteUrl, URL(string: "https://example.com/api/foo") ) XCTAssertEqual( - TestRequest(baseURL: "https://example.com/api", path: "/foo").absoluteURL, + TestRequest(baseURL: "https://example.com/api", path: "/foo").absoluteUrl, URL(string: "https://example.com/api/foo") ) XCTAssertEqual( - TestRequest(baseURL: "https://example.com/api", path: "/foo", parameters: ["p": 1]).absoluteURL, + TestRequest(baseURL: "https://example.com/api", path: "/foo", parameters: ["p": 1]).absoluteUrl, URL(string: "https://example.com/api/foo?p=1") ) XCTAssertEqual( - TestRequest(baseURL: "https://example.com/api", path: "/foo/").absoluteURL, + TestRequest(baseURL: "https://example.com/api", path: "/foo/").absoluteUrl, URL(string: "https://example.com/api/foo/") ) XCTAssertEqual( - TestRequest(baseURL: "https://example.com/api", path: "/foo/", parameters: ["p": 1]).absoluteURL, + TestRequest(baseURL: "https://example.com/api", path: "/foo/", parameters: ["p": 1]).absoluteUrl, URL(string: "https://example.com/api/foo/?p=1") ) XCTAssertEqual( - TestRequest(baseURL: "https://example.com/api", path: "foo/bar").absoluteURL, + TestRequest(baseURL: "https://example.com/api", path: "foo/bar").absoluteUrl, URL(string: "https://example.com/api/foo/bar") ) XCTAssertEqual( - TestRequest(baseURL: "https://example.com/api", path: "/foo/bar").absoluteURL, + TestRequest(baseURL: "https://example.com/api", path: "/foo/bar").absoluteUrl, URL(string: "https://example.com/api/foo/bar") ) XCTAssertEqual( - TestRequest(baseURL: "https://example.com/api", path: "/foo/bar", parameters: ["p": 1]).absoluteURL, + TestRequest(baseURL: "https://example.com/api", path: "/foo/bar", parameters: ["p": 1]).absoluteUrl, URL(string: "https://example.com/api/foo/bar?p=1") ) XCTAssertEqual( - TestRequest(baseURL: "https://example.com/api", path: "/foo/bar/").absoluteURL, + TestRequest(baseURL: "https://example.com/api", path: "/foo/bar/").absoluteUrl, URL(string: "https://example.com/api/foo/bar/") ) XCTAssertEqual( - TestRequest(baseURL: "https://example.com/api", path: "/foo/bar/", parameters: ["p": 1]).absoluteURL, + TestRequest(baseURL: "https://example.com/api", path: "/foo/bar/", parameters: ["p": 1]).absoluteUrl, URL(string: "https://example.com/api/foo/bar/?p=1") ) XCTAssertEqual( - TestRequest(baseURL: "https://example.com/api", path: "foo//bar//").absoluteURL, + TestRequest(baseURL: "https://example.com/api", path: "foo//bar//").absoluteUrl, URL(string: "https://example.com/api/foo//bar//") ) // MARK: - baseURL = https://example.com/api/ XCTAssertEqual( - TestRequest(baseURL: "https://example.com/api/", path: "").absoluteURL, + TestRequest(baseURL: "https://example.com/api/", path: "").absoluteUrl, URL(string: "https://example.com/api/") ) XCTAssertEqual( - TestRequest(baseURL: "https://example.com/api/", path: "/").absoluteURL, + TestRequest(baseURL: "https://example.com/api/", path: "/").absoluteUrl, URL(string: "https://example.com/api//") ) XCTAssertEqual( - TestRequest(baseURL: "https://example.com/api/", path: "/", parameters: ["p": 1]).absoluteURL, + TestRequest(baseURL: "https://example.com/api/", path: "/", parameters: ["p": 1]).absoluteUrl, URL(string: "https://example.com/api//?p=1") ) XCTAssertEqual( - TestRequest(baseURL: "https://example.com/api/", path: "foo").absoluteURL, + TestRequest(baseURL: "https://example.com/api/", path: "foo").absoluteUrl, URL(string: "https://example.com/api/foo") ) XCTAssertEqual( - TestRequest(baseURL: "https://example.com/api/", path: "/foo").absoluteURL, + TestRequest(baseURL: "https://example.com/api/", path: "/foo").absoluteUrl, URL(string: "https://example.com/api//foo") ) XCTAssertEqual( - TestRequest(baseURL: "https://example.com/api/", path: "/foo", parameters: ["p": 1]).absoluteURL, + TestRequest(baseURL: "https://example.com/api/", path: "/foo", parameters: ["p": 1]).absoluteUrl, URL(string: "https://example.com/api//foo?p=1") ) XCTAssertEqual( - TestRequest(baseURL: "https://example.com/api/", path: "/foo/").absoluteURL, + TestRequest(baseURL: "https://example.com/api/", path: "/foo/").absoluteUrl, URL(string: "https://example.com/api//foo/") ) XCTAssertEqual( - TestRequest(baseURL: "https://example.com/api/", path: "/foo/", parameters: ["p": 1]).absoluteURL, + TestRequest(baseURL: "https://example.com/api/", path: "/foo/", parameters: ["p": 1]).absoluteUrl, URL(string: "https://example.com/api//foo/?p=1") ) XCTAssertEqual( - TestRequest(baseURL: "https://example.com/api/", path: "foo/bar").absoluteURL, + TestRequest(baseURL: "https://example.com/api/", path: "foo/bar").absoluteUrl, URL(string: "https://example.com/api/foo/bar") ) XCTAssertEqual( - TestRequest(baseURL: "https://example.com/api/", path: "/foo/bar").absoluteURL, + TestRequest(baseURL: "https://example.com/api/", path: "/foo/bar").absoluteUrl, URL(string: "https://example.com/api//foo/bar") ) XCTAssertEqual( - TestRequest(baseURL: "https://example.com/api/", path: "/foo/bar", parameters: ["p": 1]).absoluteURL, + TestRequest(baseURL: "https://example.com/api/", path: "/foo/bar", parameters: ["p": 1]).absoluteUrl, URL(string: "https://example.com/api//foo/bar?p=1") ) XCTAssertEqual( - TestRequest(baseURL: "https://example.com/api/", path: "/foo/bar/").absoluteURL, + TestRequest(baseURL: "https://example.com/api/", path: "/foo/bar/").absoluteUrl, URL(string: "https://example.com/api//foo/bar/") ) XCTAssertEqual( - TestRequest(baseURL: "https://example.com/api/", path: "/foo/bar/", parameters: ["p": 1]).absoluteURL, + TestRequest(baseURL: "https://example.com/api/", path: "/foo/bar/", parameters: ["p": 1]).absoluteUrl, URL(string: "https://example.com/api//foo/bar/?p=1") ) XCTAssertEqual( - TestRequest(baseURL: "https://example.com/api/", path: "foo//bar//").absoluteURL, + TestRequest(baseURL: "https://example.com/api/", path: "foo//bar//").absoluteUrl, URL(string: "https://example.com/api/foo//bar//") ) // MARK: - baseURL = https://example.com/// XCTAssertEqual( - TestRequest(baseURL: "https://example.com///", path: "").absoluteURL, + TestRequest(baseURL: "https://example.com///", path: "").absoluteUrl, URL(string: "https://example.com///") ) XCTAssertEqual( - TestRequest(baseURL: "https://example.com///", path: "/").absoluteURL, + TestRequest(baseURL: "https://example.com///", path: "/").absoluteUrl, URL(string: "https://example.com////") ) XCTAssertEqual( - TestRequest(baseURL: "https://example.com///", path: "/", parameters: ["p": 1]).absoluteURL, + TestRequest(baseURL: "https://example.com///", path: "/", parameters: ["p": 1]).absoluteUrl, URL(string: "https://example.com////?p=1") ) XCTAssertEqual( - TestRequest(baseURL: "https://example.com///", path: "foo").absoluteURL, + TestRequest(baseURL: "https://example.com///", path: "foo").absoluteUrl, URL(string: "https://example.com///foo") ) XCTAssertEqual( - TestRequest(baseURL: "https://example.com///", path: "/foo").absoluteURL, + TestRequest(baseURL: "https://example.com///", path: "/foo").absoluteUrl, URL(string: "https://example.com////foo") ) XCTAssertEqual( - TestRequest(baseURL: "https://example.com///", path: "/foo", parameters: ["p": 1]).absoluteURL, + TestRequest(baseURL: "https://example.com///", path: "/foo", parameters: ["p": 1]).absoluteUrl, URL(string: "https://example.com////foo?p=1") ) XCTAssertEqual( - TestRequest(baseURL: "https://example.com///", path: "/foo/").absoluteURL, + TestRequest(baseURL: "https://example.com///", path: "/foo/").absoluteUrl, URL(string: "https://example.com////foo/") ) XCTAssertEqual( - TestRequest(baseURL: "https://example.com///", path: "/foo/", parameters: ["p": 1]).absoluteURL, + TestRequest(baseURL: "https://example.com///", path: "/foo/", parameters: ["p": 1]).absoluteUrl, URL(string: "https://example.com////foo/?p=1") ) XCTAssertEqual( - TestRequest(baseURL: "https://example.com///", path: "foo/bar").absoluteURL, + TestRequest(baseURL: "https://example.com///", path: "foo/bar").absoluteUrl, URL(string: "https://example.com///foo/bar") ) XCTAssertEqual( - TestRequest(baseURL: "https://example.com///", path: "/foo/bar").absoluteURL, + TestRequest(baseURL: "https://example.com///", path: "/foo/bar").absoluteUrl, URL(string: "https://example.com////foo/bar") ) XCTAssertEqual( - TestRequest(baseURL: "https://example.com///", path: "/foo/bar", parameters: ["p": 1]).absoluteURL, + TestRequest(baseURL: "https://example.com///", path: "/foo/bar", parameters: ["p": 1]).absoluteUrl, URL(string: "https://example.com////foo/bar?p=1") ) XCTAssertEqual( - TestRequest(baseURL: "https://example.com///", path: "/foo/bar/").absoluteURL, + TestRequest(baseURL: "https://example.com///", path: "/foo/bar/").absoluteUrl, URL(string: "https://example.com////foo/bar/") ) XCTAssertEqual( - TestRequest(baseURL: "https://example.com///", path: "/foo/bar/", parameters: ["p": 1]).absoluteURL, + TestRequest(baseURL: "https://example.com///", path: "/foo/bar/", parameters: ["p": 1]).absoluteUrl, URL(string: "https://example.com////foo/bar/?p=1") ) XCTAssertEqual( - TestRequest(baseURL: "https://example.com///", path: "foo//bar//").absoluteURL, + TestRequest(baseURL: "https://example.com///", path: "foo//bar//").absoluteUrl, URL(string: "https://example.com///foo//bar//") ) } diff --git a/Tests/APIKit/TestComponents/TestRequest.swift b/Tests/APIKit/TestComponents/TestRequest.swift index eeca4a01..4250cecb 100644 --- a/Tests/APIKit/TestComponents/TestRequest.swift +++ b/Tests/APIKit/TestComponents/TestRequest.swift @@ -2,7 +2,7 @@ import Foundation import APIKit struct TestRequest: RequestType { - var absoluteURL: URL? { + var absoluteUrl: URL? { let urlRequest = try? buildURLRequest() return urlRequest?.url } From e830360678864d2db4cf44891c1c703c7caf37a3 Mon Sep 17 00:00:00 2001 From: Syo Ikeda Date: Mon, 8 Aug 2016 22:58:34 +0900 Subject: [PATCH 10/38] Rename baseURL to baseUrl --- Demo.playground/Contents.swift | 2 +- Sources/Error/RequestError.swift | 2 +- Sources/RequestType.swift | 8 +- Tests/APIKit/RequestTypeTests.swift | 148 +++++++++--------- Tests/APIKit/SessionTests.swift | 2 +- Tests/APIKit/TestComponents/TestRequest.swift | 6 +- 6 files changed, 84 insertions(+), 84 deletions(-) diff --git a/Demo.playground/Contents.swift b/Demo.playground/Contents.swift index 3279d6a4..06ac452e 100644 --- a/Demo.playground/Contents.swift +++ b/Demo.playground/Contents.swift @@ -10,7 +10,7 @@ protocol GitHubRequestType: RequestType { } extension GitHubRequestType { - var baseURL: URL { + var baseUrl: URL { return URL(string: "https://api.github.com")! } } diff --git a/Sources/Error/RequestError.swift b/Sources/Error/RequestError.swift index ded40ee2..17870ba2 100644 --- a/Sources/Error/RequestError.swift +++ b/Sources/Error/RequestError.swift @@ -2,7 +2,7 @@ import Foundation /// `RequestError` represents a common error that occurs while building `URLRequest` from `RequestType`. public enum RequestError: Error { - /// Indicates `baseURL` of a type that conforms `RequestType` is invalid. + /// Indicates `baseUrl` of a type that conforms `RequestType` is invalid. case InvalidBaseURL(URL) /// Indicates `URLRequest` built by `RequestType.buildURLRequest` is unexpected. diff --git a/Sources/RequestType.swift b/Sources/RequestType.swift index b817d65c..b2c321db 100644 --- a/Sources/RequestType.swift +++ b/Sources/RequestType.swift @@ -4,7 +4,7 @@ import Result /// `RequestType` protocol represents a request for Web API. /// Following 5 items must be implemented. /// - `typealias Response` -/// - `var baseURL: URL` +/// - `var baseUrl: URL` /// - `var method: HTTPMethod` /// - `var path: String` /// - `func responseFromObject(object: AnyObject, urlResponse: HTTPURLResponse) throws -> Response` @@ -13,7 +13,7 @@ public protocol RequestType { associatedtype Response /// The base URL. - var baseURL: URL { get } + var baseUrl: URL { get } /// The HTTP request method. var method: HTTPMethod { get } @@ -104,9 +104,9 @@ public extension RequestType { /// Builds `URLRequest` from properties of `self`. /// - Throws: `RequestError`, `ErrorType` public func buildURLRequest() throws -> URLRequest { - let url = path.isEmpty ? baseURL : baseURL.appendingPathComponent(path) + let url = path.isEmpty ? baseUrl : baseUrl.appendingPathComponent(path) guard var components = URLComponents(url: url, resolvingAgainstBaseURL: true) else { - throw RequestError.InvalidBaseURL(baseURL) + throw RequestError.InvalidBaseURL(baseUrl) } var urlRequest = URLRequest(url: url) diff --git a/Tests/APIKit/RequestTypeTests.swift b/Tests/APIKit/RequestTypeTests.swift index 9a26c6ae..2e0faf8e 100644 --- a/Tests/APIKit/RequestTypeTests.swift +++ b/Tests/APIKit/RequestTypeTests.swift @@ -58,353 +58,353 @@ class RequestTypeTests: XCTestCase { } func testBuildURL() { - // MARK: - baseURL = https://example.com + // MARK: - baseUrl = https://example.com XCTAssertEqual( - TestRequest(baseURL: "https://example.com", path: "").absoluteUrl, + TestRequest(baseUrl: "https://example.com", path: "").absoluteUrl, URL(string: "https://example.com") ) XCTAssertEqual( - TestRequest(baseURL: "https://example.com", path: "/").absoluteUrl, + TestRequest(baseUrl: "https://example.com", path: "/").absoluteUrl, URL(string: "https://example.com/") ) XCTAssertEqual( - TestRequest(baseURL: "https://example.com", path: "/", parameters: ["p": 1]).absoluteUrl, + TestRequest(baseUrl: "https://example.com", path: "/", parameters: ["p": 1]).absoluteUrl, URL(string: "https://example.com/?p=1") ) XCTAssertEqual( - TestRequest(baseURL: "https://example.com", path: "foo").absoluteUrl, + TestRequest(baseUrl: "https://example.com", path: "foo").absoluteUrl, URL(string: "https://example.com/foo") ) XCTAssertEqual( - TestRequest(baseURL: "https://example.com", path: "/foo", parameters: ["p": 1]).absoluteUrl, + TestRequest(baseUrl: "https://example.com", path: "/foo", parameters: ["p": 1]).absoluteUrl, URL(string: "https://example.com/foo?p=1") ) XCTAssertEqual( - TestRequest(baseURL: "https://example.com", path: "/foo/").absoluteUrl, + TestRequest(baseUrl: "https://example.com", path: "/foo/").absoluteUrl, URL(string: "https://example.com/foo/") ) XCTAssertEqual( - TestRequest(baseURL: "https://example.com", path: "/foo/", parameters: ["p": 1]).absoluteUrl, + TestRequest(baseUrl: "https://example.com", path: "/foo/", parameters: ["p": 1]).absoluteUrl, URL(string: "https://example.com/foo/?p=1") ) XCTAssertEqual( - TestRequest(baseURL: "https://example.com", path: "foo/bar").absoluteUrl, + TestRequest(baseUrl: "https://example.com", path: "foo/bar").absoluteUrl, URL(string: "https://example.com/foo/bar") ) XCTAssertEqual( - TestRequest(baseURL: "https://example.com", path: "/foo/bar").absoluteUrl, + TestRequest(baseUrl: "https://example.com", path: "/foo/bar").absoluteUrl, URL(string: "https://example.com/foo/bar") ) XCTAssertEqual( - TestRequest(baseURL: "https://example.com", path: "/foo/bar", parameters: ["p": 1]).absoluteUrl, + TestRequest(baseUrl: "https://example.com", path: "/foo/bar", parameters: ["p": 1]).absoluteUrl, URL(string: "https://example.com/foo/bar?p=1") ) XCTAssertEqual( - TestRequest(baseURL: "https://example.com", path: "/foo/bar/").absoluteUrl, + TestRequest(baseUrl: "https://example.com", path: "/foo/bar/").absoluteUrl, URL(string: "https://example.com/foo/bar/") ) XCTAssertEqual( - TestRequest(baseURL: "https://example.com", path: "/foo/bar/", parameters: ["p": 1]).absoluteUrl, + TestRequest(baseUrl: "https://example.com", path: "/foo/bar/", parameters: ["p": 1]).absoluteUrl, URL(string: "https://example.com/foo/bar/?p=1") ) XCTAssertEqual( - TestRequest(baseURL: "https://example.com", path: "/foo/bar//").absoluteUrl, + TestRequest(baseUrl: "https://example.com", path: "/foo/bar//").absoluteUrl, URL(string: "https://example.com/foo/bar//") ) - // MARK: - baseURL = https://example.com/ + // MARK: - baseUrl = https://example.com/ XCTAssertEqual( - TestRequest(baseURL: "https://example.com/", path: "").absoluteUrl, + TestRequest(baseUrl: "https://example.com/", path: "").absoluteUrl, URL(string: "https://example.com/") ) XCTAssertEqual( - TestRequest(baseURL: "https://example.com/", path: "/").absoluteUrl, + TestRequest(baseUrl: "https://example.com/", path: "/").absoluteUrl, URL(string: "https://example.com//") ) XCTAssertEqual( - TestRequest(baseURL: "https://example.com/", path: "/", parameters: ["p": 1]).absoluteUrl, + TestRequest(baseUrl: "https://example.com/", path: "/", parameters: ["p": 1]).absoluteUrl, URL(string: "https://example.com//?p=1") ) XCTAssertEqual( - TestRequest(baseURL: "https://example.com/", path: "foo").absoluteUrl, + TestRequest(baseUrl: "https://example.com/", path: "foo").absoluteUrl, URL(string: "https://example.com/foo") ) XCTAssertEqual( - TestRequest(baseURL: "https://example.com/", path: "/foo").absoluteUrl, + TestRequest(baseUrl: "https://example.com/", path: "/foo").absoluteUrl, URL(string: "https://example.com//foo") ) XCTAssertEqual( - TestRequest(baseURL: "https://example.com/", path: "/foo", parameters: ["p": 1]).absoluteUrl, + TestRequest(baseUrl: "https://example.com/", path: "/foo", parameters: ["p": 1]).absoluteUrl, URL(string: "https://example.com//foo?p=1") ) XCTAssertEqual( - TestRequest(baseURL: "https://example.com/", path: "/foo/").absoluteUrl, + TestRequest(baseUrl: "https://example.com/", path: "/foo/").absoluteUrl, URL(string: "https://example.com//foo/") ) XCTAssertEqual( - TestRequest(baseURL: "https://example.com/", path: "/foo/", parameters: ["p": 1]).absoluteUrl, + TestRequest(baseUrl: "https://example.com/", path: "/foo/", parameters: ["p": 1]).absoluteUrl, URL(string: "https://example.com//foo/?p=1") ) XCTAssertEqual( - TestRequest(baseURL: "https://example.com/", path: "foo/bar").absoluteUrl, + TestRequest(baseUrl: "https://example.com/", path: "foo/bar").absoluteUrl, URL(string: "https://example.com/foo/bar") ) XCTAssertEqual( - TestRequest(baseURL: "https://example.com/", path: "/foo/bar").absoluteUrl, + TestRequest(baseUrl: "https://example.com/", path: "/foo/bar").absoluteUrl, URL(string: "https://example.com//foo/bar") ) XCTAssertEqual( - TestRequest(baseURL: "https://example.com/", path: "/foo/bar", parameters: ["p": 1]).absoluteUrl, + TestRequest(baseUrl: "https://example.com/", path: "/foo/bar", parameters: ["p": 1]).absoluteUrl, URL(string: "https://example.com//foo/bar?p=1") ) XCTAssertEqual( - TestRequest(baseURL: "https://example.com/", path: "/foo/bar/").absoluteUrl, + TestRequest(baseUrl: "https://example.com/", path: "/foo/bar/").absoluteUrl, URL(string: "https://example.com//foo/bar/") ) XCTAssertEqual( - TestRequest(baseURL: "https://example.com/", path: "/foo/bar/", parameters: ["p": 1]).absoluteUrl, + TestRequest(baseUrl: "https://example.com/", path: "/foo/bar/", parameters: ["p": 1]).absoluteUrl, URL(string: "https://example.com//foo/bar/?p=1") ) XCTAssertEqual( - TestRequest(baseURL: "https://example.com/", path: "foo//bar//").absoluteUrl, + TestRequest(baseUrl: "https://example.com/", path: "foo//bar//").absoluteUrl, URL(string: "https://example.com/foo//bar//") ) - // MARK: - baseURL = https://example.com/api + // MARK: - baseUrl = https://example.com/api XCTAssertEqual( - TestRequest(baseURL: "https://example.com/api", path: "").absoluteUrl, + TestRequest(baseUrl: "https://example.com/api", path: "").absoluteUrl, URL(string: "https://example.com/api") ) XCTAssertEqual( - TestRequest(baseURL: "https://example.com/api", path: "/").absoluteUrl, + TestRequest(baseUrl: "https://example.com/api", path: "/").absoluteUrl, URL(string: "https://example.com/api/") ) XCTAssertEqual( - TestRequest(baseURL: "https://example.com/api", path: "/", parameters: ["p": 1]).absoluteUrl, + TestRequest(baseUrl: "https://example.com/api", path: "/", parameters: ["p": 1]).absoluteUrl, URL(string: "https://example.com/api/?p=1") ) XCTAssertEqual( - TestRequest(baseURL: "https://example.com/api", path: "foo").absoluteUrl, + TestRequest(baseUrl: "https://example.com/api", path: "foo").absoluteUrl, URL(string: "https://example.com/api/foo") ) XCTAssertEqual( - TestRequest(baseURL: "https://example.com/api", path: "/foo").absoluteUrl, + TestRequest(baseUrl: "https://example.com/api", path: "/foo").absoluteUrl, URL(string: "https://example.com/api/foo") ) XCTAssertEqual( - TestRequest(baseURL: "https://example.com/api", path: "/foo", parameters: ["p": 1]).absoluteUrl, + TestRequest(baseUrl: "https://example.com/api", path: "/foo", parameters: ["p": 1]).absoluteUrl, URL(string: "https://example.com/api/foo?p=1") ) XCTAssertEqual( - TestRequest(baseURL: "https://example.com/api", path: "/foo/").absoluteUrl, + TestRequest(baseUrl: "https://example.com/api", path: "/foo/").absoluteUrl, URL(string: "https://example.com/api/foo/") ) XCTAssertEqual( - TestRequest(baseURL: "https://example.com/api", path: "/foo/", parameters: ["p": 1]).absoluteUrl, + TestRequest(baseUrl: "https://example.com/api", path: "/foo/", parameters: ["p": 1]).absoluteUrl, URL(string: "https://example.com/api/foo/?p=1") ) XCTAssertEqual( - TestRequest(baseURL: "https://example.com/api", path: "foo/bar").absoluteUrl, + TestRequest(baseUrl: "https://example.com/api", path: "foo/bar").absoluteUrl, URL(string: "https://example.com/api/foo/bar") ) XCTAssertEqual( - TestRequest(baseURL: "https://example.com/api", path: "/foo/bar").absoluteUrl, + TestRequest(baseUrl: "https://example.com/api", path: "/foo/bar").absoluteUrl, URL(string: "https://example.com/api/foo/bar") ) XCTAssertEqual( - TestRequest(baseURL: "https://example.com/api", path: "/foo/bar", parameters: ["p": 1]).absoluteUrl, + TestRequest(baseUrl: "https://example.com/api", path: "/foo/bar", parameters: ["p": 1]).absoluteUrl, URL(string: "https://example.com/api/foo/bar?p=1") ) XCTAssertEqual( - TestRequest(baseURL: "https://example.com/api", path: "/foo/bar/").absoluteUrl, + TestRequest(baseUrl: "https://example.com/api", path: "/foo/bar/").absoluteUrl, URL(string: "https://example.com/api/foo/bar/") ) XCTAssertEqual( - TestRequest(baseURL: "https://example.com/api", path: "/foo/bar/", parameters: ["p": 1]).absoluteUrl, + TestRequest(baseUrl: "https://example.com/api", path: "/foo/bar/", parameters: ["p": 1]).absoluteUrl, URL(string: "https://example.com/api/foo/bar/?p=1") ) XCTAssertEqual( - TestRequest(baseURL: "https://example.com/api", path: "foo//bar//").absoluteUrl, + TestRequest(baseUrl: "https://example.com/api", path: "foo//bar//").absoluteUrl, URL(string: "https://example.com/api/foo//bar//") ) - // MARK: - baseURL = https://example.com/api/ + // MARK: - baseUrl = https://example.com/api/ XCTAssertEqual( - TestRequest(baseURL: "https://example.com/api/", path: "").absoluteUrl, + TestRequest(baseUrl: "https://example.com/api/", path: "").absoluteUrl, URL(string: "https://example.com/api/") ) XCTAssertEqual( - TestRequest(baseURL: "https://example.com/api/", path: "/").absoluteUrl, + TestRequest(baseUrl: "https://example.com/api/", path: "/").absoluteUrl, URL(string: "https://example.com/api//") ) XCTAssertEqual( - TestRequest(baseURL: "https://example.com/api/", path: "/", parameters: ["p": 1]).absoluteUrl, + TestRequest(baseUrl: "https://example.com/api/", path: "/", parameters: ["p": 1]).absoluteUrl, URL(string: "https://example.com/api//?p=1") ) XCTAssertEqual( - TestRequest(baseURL: "https://example.com/api/", path: "foo").absoluteUrl, + TestRequest(baseUrl: "https://example.com/api/", path: "foo").absoluteUrl, URL(string: "https://example.com/api/foo") ) XCTAssertEqual( - TestRequest(baseURL: "https://example.com/api/", path: "/foo").absoluteUrl, + TestRequest(baseUrl: "https://example.com/api/", path: "/foo").absoluteUrl, URL(string: "https://example.com/api//foo") ) XCTAssertEqual( - TestRequest(baseURL: "https://example.com/api/", path: "/foo", parameters: ["p": 1]).absoluteUrl, + TestRequest(baseUrl: "https://example.com/api/", path: "/foo", parameters: ["p": 1]).absoluteUrl, URL(string: "https://example.com/api//foo?p=1") ) XCTAssertEqual( - TestRequest(baseURL: "https://example.com/api/", path: "/foo/").absoluteUrl, + TestRequest(baseUrl: "https://example.com/api/", path: "/foo/").absoluteUrl, URL(string: "https://example.com/api//foo/") ) XCTAssertEqual( - TestRequest(baseURL: "https://example.com/api/", path: "/foo/", parameters: ["p": 1]).absoluteUrl, + TestRequest(baseUrl: "https://example.com/api/", path: "/foo/", parameters: ["p": 1]).absoluteUrl, URL(string: "https://example.com/api//foo/?p=1") ) XCTAssertEqual( - TestRequest(baseURL: "https://example.com/api/", path: "foo/bar").absoluteUrl, + TestRequest(baseUrl: "https://example.com/api/", path: "foo/bar").absoluteUrl, URL(string: "https://example.com/api/foo/bar") ) XCTAssertEqual( - TestRequest(baseURL: "https://example.com/api/", path: "/foo/bar").absoluteUrl, + TestRequest(baseUrl: "https://example.com/api/", path: "/foo/bar").absoluteUrl, URL(string: "https://example.com/api//foo/bar") ) XCTAssertEqual( - TestRequest(baseURL: "https://example.com/api/", path: "/foo/bar", parameters: ["p": 1]).absoluteUrl, + TestRequest(baseUrl: "https://example.com/api/", path: "/foo/bar", parameters: ["p": 1]).absoluteUrl, URL(string: "https://example.com/api//foo/bar?p=1") ) XCTAssertEqual( - TestRequest(baseURL: "https://example.com/api/", path: "/foo/bar/").absoluteUrl, + TestRequest(baseUrl: "https://example.com/api/", path: "/foo/bar/").absoluteUrl, URL(string: "https://example.com/api//foo/bar/") ) XCTAssertEqual( - TestRequest(baseURL: "https://example.com/api/", path: "/foo/bar/", parameters: ["p": 1]).absoluteUrl, + TestRequest(baseUrl: "https://example.com/api/", path: "/foo/bar/", parameters: ["p": 1]).absoluteUrl, URL(string: "https://example.com/api//foo/bar/?p=1") ) XCTAssertEqual( - TestRequest(baseURL: "https://example.com/api/", path: "foo//bar//").absoluteUrl, + TestRequest(baseUrl: "https://example.com/api/", path: "foo//bar//").absoluteUrl, URL(string: "https://example.com/api/foo//bar//") ) - // MARK: - baseURL = https://example.com/// + // MARK: - baseUrl = https://example.com/// XCTAssertEqual( - TestRequest(baseURL: "https://example.com///", path: "").absoluteUrl, + TestRequest(baseUrl: "https://example.com///", path: "").absoluteUrl, URL(string: "https://example.com///") ) XCTAssertEqual( - TestRequest(baseURL: "https://example.com///", path: "/").absoluteUrl, + TestRequest(baseUrl: "https://example.com///", path: "/").absoluteUrl, URL(string: "https://example.com////") ) XCTAssertEqual( - TestRequest(baseURL: "https://example.com///", path: "/", parameters: ["p": 1]).absoluteUrl, + TestRequest(baseUrl: "https://example.com///", path: "/", parameters: ["p": 1]).absoluteUrl, URL(string: "https://example.com////?p=1") ) XCTAssertEqual( - TestRequest(baseURL: "https://example.com///", path: "foo").absoluteUrl, + TestRequest(baseUrl: "https://example.com///", path: "foo").absoluteUrl, URL(string: "https://example.com///foo") ) XCTAssertEqual( - TestRequest(baseURL: "https://example.com///", path: "/foo").absoluteUrl, + TestRequest(baseUrl: "https://example.com///", path: "/foo").absoluteUrl, URL(string: "https://example.com////foo") ) XCTAssertEqual( - TestRequest(baseURL: "https://example.com///", path: "/foo", parameters: ["p": 1]).absoluteUrl, + TestRequest(baseUrl: "https://example.com///", path: "/foo", parameters: ["p": 1]).absoluteUrl, URL(string: "https://example.com////foo?p=1") ) XCTAssertEqual( - TestRequest(baseURL: "https://example.com///", path: "/foo/").absoluteUrl, + TestRequest(baseUrl: "https://example.com///", path: "/foo/").absoluteUrl, URL(string: "https://example.com////foo/") ) XCTAssertEqual( - TestRequest(baseURL: "https://example.com///", path: "/foo/", parameters: ["p": 1]).absoluteUrl, + TestRequest(baseUrl: "https://example.com///", path: "/foo/", parameters: ["p": 1]).absoluteUrl, URL(string: "https://example.com////foo/?p=1") ) XCTAssertEqual( - TestRequest(baseURL: "https://example.com///", path: "foo/bar").absoluteUrl, + TestRequest(baseUrl: "https://example.com///", path: "foo/bar").absoluteUrl, URL(string: "https://example.com///foo/bar") ) XCTAssertEqual( - TestRequest(baseURL: "https://example.com///", path: "/foo/bar").absoluteUrl, + TestRequest(baseUrl: "https://example.com///", path: "/foo/bar").absoluteUrl, URL(string: "https://example.com////foo/bar") ) XCTAssertEqual( - TestRequest(baseURL: "https://example.com///", path: "/foo/bar", parameters: ["p": 1]).absoluteUrl, + TestRequest(baseUrl: "https://example.com///", path: "/foo/bar", parameters: ["p": 1]).absoluteUrl, URL(string: "https://example.com////foo/bar?p=1") ) XCTAssertEqual( - TestRequest(baseURL: "https://example.com///", path: "/foo/bar/").absoluteUrl, + TestRequest(baseUrl: "https://example.com///", path: "/foo/bar/").absoluteUrl, URL(string: "https://example.com////foo/bar/") ) XCTAssertEqual( - TestRequest(baseURL: "https://example.com///", path: "/foo/bar/", parameters: ["p": 1]).absoluteUrl, + TestRequest(baseUrl: "https://example.com///", path: "/foo/bar/", parameters: ["p": 1]).absoluteUrl, URL(string: "https://example.com////foo/bar/?p=1") ) XCTAssertEqual( - TestRequest(baseURL: "https://example.com///", path: "foo//bar//").absoluteUrl, + TestRequest(baseUrl: "https://example.com///", path: "foo//bar//").absoluteUrl, URL(string: "https://example.com///foo//bar//") ) } diff --git a/Tests/APIKit/SessionTests.swift b/Tests/APIKit/SessionTests.swift index f0fe5076..7edb92df 100644 --- a/Tests/APIKit/SessionTests.swift +++ b/Tests/APIKit/SessionTests.swift @@ -179,7 +179,7 @@ class SessionTests: XCTestCase { struct AnotherTestRequest: RequestType { typealias Response = Void - var baseURL: URL { + var baseUrl: URL { return URL(string: "https://example.com")! } diff --git a/Tests/APIKit/TestComponents/TestRequest.swift b/Tests/APIKit/TestComponents/TestRequest.swift index 4250cecb..142efe3a 100644 --- a/Tests/APIKit/TestComponents/TestRequest.swift +++ b/Tests/APIKit/TestComponents/TestRequest.swift @@ -10,8 +10,8 @@ struct TestRequest: RequestType { // MARK: RequestType typealias Response = AnyObject - init(baseURL: String = "https://example.com", path: String = "/", method: HTTPMethod = .GET, parameters: AnyObject? = [:], headerFields: [String: String] = [:], interceptURLRequest: (URLRequest) throws -> URLRequest = { $0 }) { - self.baseURL = URL(string: baseURL)! + init(baseUrl: String = "https://example.com", path: String = "/", method: HTTPMethod = .GET, parameters: AnyObject? = [:], headerFields: [String: String] = [:], interceptURLRequest: (URLRequest) throws -> URLRequest = { $0 }) { + self.baseUrl = URL(string: baseUrl)! self.path = path self.method = method self.parameters = parameters @@ -19,7 +19,7 @@ struct TestRequest: RequestType { self.interceptURLRequest = interceptURLRequest } - let baseURL: URL + let baseUrl: URL let method: HTTPMethod let path: String let parameters: AnyObject? From 04f08bacb5273a158f05e8abc87a3b92b020a7ab Mon Sep 17 00:00:00 2001 From: Syo Ikeda Date: Mon, 8 Aug 2016 23:03:38 +0900 Subject: [PATCH 11/38] [TestSessionAdapter] Rename URLResponse to urlResponse --- Tests/APIKit/SessionTests.swift | 8 ++++---- Tests/APIKit/TestComponents/TestSessionAdapter.swift | 8 ++++---- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/Tests/APIKit/SessionTests.swift b/Tests/APIKit/SessionTests.swift index 7edb92df..2513ffb0 100644 --- a/Tests/APIKit/SessionTests.swift +++ b/Tests/APIKit/SessionTests.swift @@ -60,7 +60,7 @@ class SessionTests: XCTestCase { } func testUnacceptableStatusCodeError() { - adapter.URLResponse = HTTPURLResponse(url: NSURL(string: "")! as URL, statusCode: 400, httpVersion: nil, headerFields: nil) + adapter.urlResponse = HTTPURLResponse(url: NSURL(string: "")! as URL, statusCode: 400, httpVersion: nil, headerFields: nil) let expectation = self.expectation(description: "wait for response") let request = TestRequest() @@ -81,7 +81,7 @@ class SessionTests: XCTestCase { } func testNonHTTPURLResponseError() { - adapter.URLResponse = URLResponse() + adapter.urlResponse = URLResponse() let expectation = self.expectation(description: "wait for response") let request = TestRequest() @@ -89,8 +89,8 @@ class SessionTests: XCTestCase { session.sendRequest(request) { result in if case .failure(let error) = result, case .ResponseError(let responseError as ResponseError) = error, - case .NonHTTPURLResponse(let URLResponse) = responseError { - XCTAssert(URLResponse === self.adapter.URLResponse) + case .NonHTTPURLResponse(let urlResponse) = responseError { + XCTAssert(urlResponse === self.adapter.urlResponse) } else { XCTFail() } diff --git a/Tests/APIKit/TestComponents/TestSessionAdapter.swift b/Tests/APIKit/TestComponents/TestSessionAdapter.swift index a0e3c939..89c2cfb1 100644 --- a/Tests/APIKit/TestComponents/TestSessionAdapter.swift +++ b/Tests/APIKit/TestComponents/TestSessionAdapter.swift @@ -7,7 +7,7 @@ class TestSessionAdapter: SessionAdapterType { } var data: Data? - var URLResponse: URLResponse? + var urlResponse: URLResponse? var error: Error? private class Runner { @@ -22,9 +22,9 @@ class TestSessionAdapter: SessionAdapterType { private let runner: Runner private let timer: Timer - init(data: Data? = Data(), URLResponse: URLResponse? = HTTPURLResponse(url: NSURL(string: "")! as URL, statusCode: 200, httpVersion: nil, headerFields: nil), error: Error? = nil) { + init(data: Data? = Data(), urlResponse: URLResponse? = HTTPURLResponse(url: NSURL(string: "")! as URL, statusCode: 200, httpVersion: nil, headerFields: nil), error: Error? = nil) { self.data = data - self.URLResponse = URLResponse + self.urlResponse = urlResponse self.error = error self.runner = Runner() @@ -42,7 +42,7 @@ class TestSessionAdapter: SessionAdapterType { if task.cancelled { task.handler(nil, nil, Error.cancelled) } else { - task.handler(data, URLResponse, error) + task.handler(data, urlResponse, error) } } From d86f8efb4c28badfc06b1326dcf92e64eb76231a Mon Sep 17 00:00:00 2001 From: Syo Ikeda Date: Mon, 8 Aug 2016 23:04:22 +0900 Subject: [PATCH 12/38] One more rename --- Tests/APIKit/RequestTypeTests.swift | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Tests/APIKit/RequestTypeTests.swift b/Tests/APIKit/RequestTypeTests.swift index 2e0faf8e..bc4c4c30 100644 --- a/Tests/APIKit/RequestTypeTests.swift +++ b/Tests/APIKit/RequestTypeTests.swift @@ -410,11 +410,11 @@ class RequestTypeTests: XCTestCase { } func testInterceptURLRequest() { - let URL = Foundation.URL(string: "https://example.com/customize")! + let url = URL(string: "https://example.com/customize")! let request = TestRequest() { _ in - return URLRequest(url: URL) + return URLRequest(url: url) } - XCTAssertEqual((try? request.buildURLRequest())?.url, URL) + XCTAssertEqual((try? request.buildURLRequest())?.url, url) } } From 8dccd99fa4123e054a36f2b060fbfa0f68bd6ef9 Mon Sep 17 00:00:00 2001 From: Syo Ikeda Date: Mon, 8 Aug 2016 23:07:58 +0900 Subject: [PATCH 13/38] [Travis] Use `build-for-testing` and `test-without-building` build actions This should stabilize running iOS and tvOS tests on Travis with Xcode 8. --- .travis.yml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/.travis.yml b/.travis.yml index d3759ecd..07f23bd2 100644 --- a/.travis.yml +++ b/.travis.yml @@ -17,9 +17,9 @@ install: script: - if [[ "$JOB" == "Xcode7.3" ]]; then pod lib lint; fi - set -o pipefail - - xcodebuild test -workspace APIKit.xcworkspace -scheme APIKit | xcpretty -c - - xcodebuild test -workspace APIKit.xcworkspace -scheme APIKit -sdk iphonesimulator -destination "name=iPhone 6s" | xcpretty -c - - xcodebuild test -workspace APIKit.xcworkspace -scheme APIKit -sdk appletvsimulator -destination "name=Apple TV 1080p" | xcpretty -c + - xcodebuild build-for-testing test-without-building -workspace APIKit.xcworkspace -scheme APIKit | xcpretty -c + - xcodebuild build-for-testing test-without-building -workspace APIKit.xcworkspace -scheme APIKit -sdk iphonesimulator -destination "name=iPhone 6s" | xcpretty -c + - xcodebuild build-for-testing test-without-building -workspace APIKit.xcworkspace -scheme APIKit -sdk appletvsimulator -destination "name=Apple TV 1080p" | xcpretty -c - carthage build --no-skip-current after_success: From c59610be67293b6519f870eb758c8e866de85625 Mon Sep 17 00:00:00 2001 From: Syo Ikeda Date: Mon, 8 Aug 2016 23:20:01 +0900 Subject: [PATCH 14/38] Distinguish between `Swift.min()` and `Sequence.min()` --- Sources/BodyParametersType/NSData+NSInputStream.swift | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/Sources/BodyParametersType/NSData+NSInputStream.swift b/Sources/BodyParametersType/NSData+NSInputStream.swift index 54549461..8e812154 100644 --- a/Sources/BodyParametersType/NSData+NSInputStream.swift +++ b/Sources/BodyParametersType/NSData+NSInputStream.swift @@ -9,7 +9,7 @@ extension Data { init(inputStream: InputStream, capacity: Int = Int(UInt16.max)) throws { var data = Data(capacity: capacity) - let bufferSize = _min(Int(UInt16.max), capacity) + let bufferSize = Swift.min(Int(UInt16.max), capacity) let buffer = UnsafeMutablePointer.allocate(capacity: bufferSize) var readSize: Int @@ -34,7 +34,3 @@ extension Data { self.init(data) } } - -private func _min(_ x: Int, _ y: Int) -> Int { - return y < x ? y : x -} From 26f3aa44a486753c64021eef6e9865702aea6ba5 Mon Sep 17 00:00:00 2001 From: Syo Ikeda Date: Tue, 9 Aug 2016 08:54:38 +0900 Subject: [PATCH 15/38] Remove NS prefixes from some files --- APIKit.xcodeproj/project.pbxproj | 24 +++++++++---------- ...putStream.swift => Data+InputStream.swift} | 0 ...t => URLSessionAdapterSubclassTests.swift} | 0 ...sts.swift => URLSessionAdapterTests.swift} | 0 4 files changed, 12 insertions(+), 12 deletions(-) rename Sources/BodyParametersType/{NSData+NSInputStream.swift => Data+InputStream.swift} (100%) rename Tests/APIKit/SessionAdapterType/{NSURLSessionAdapterSubclassTests.swift => URLSessionAdapterSubclassTests.swift} (100%) rename Tests/APIKit/SessionAdapterType/{NSURLSessionAdapterTests.swift => URLSessionAdapterTests.swift} (100%) diff --git a/APIKit.xcodeproj/project.pbxproj b/APIKit.xcodeproj/project.pbxproj index 094c7c4c..2d903a10 100644 --- a/APIKit.xcodeproj/project.pbxproj +++ b/APIKit.xcodeproj/project.pbxproj @@ -19,8 +19,8 @@ 7F18BD111C972C69003A31DF /* JSONBodyParameters.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7F18BD101C972C69003A31DF /* JSONBodyParameters.swift */; }; 7F18BD131C972E5A003A31DF /* FormURLEncodedBodyParameters.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7F18BD121C972E5A003A31DF /* FormURLEncodedBodyParameters.swift */; }; 7F18BD1A1C9730ED003A31DF /* URLEncodedSerialization.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7F18BD181C9730ED003A31DF /* URLEncodedSerialization.swift */; }; - 7F2001D71CF49F3000C5D0EE /* NSURLSessionAdapterSubclassTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7F2001D61CF49F3000C5D0EE /* NSURLSessionAdapterSubclassTests.swift */; }; - 7F2A15BD1CEB5F67009A12A2 /* NSData+NSInputStream.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7F2A15BC1CEB5F67009A12A2 /* NSData+NSInputStream.swift */; }; + 7F2001D71CF49F3000C5D0EE /* URLSessionAdapterSubclassTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7F2001D61CF49F3000C5D0EE /* URLSessionAdapterSubclassTests.swift */; }; + 7F2A15BD1CEB5F67009A12A2 /* Data+InputStream.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7F2A15BC1CEB5F67009A12A2 /* Data+InputStream.swift */; }; 7F2A537A1CF52165000353F0 /* test.json in Resources */ = {isa = PBXBuildFile; fileRef = 7F2A53791CF52165000353F0 /* test.json */; }; 7F2A537C1CF5D55D000353F0 /* URLEncodedSerializationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7F2A537B1CF5D55D000353F0 /* URLEncodedSerializationTests.swift */; }; 7F7E8F151C8AD4B1008A13A9 /* APIKit.h in Headers */ = {isa = PBXBuildFile; fileRef = 7F7E8F0B1C8AD4B1008A13A9 /* APIKit.h */; settings = {ATTRIBUTES = (Public, ); }; }; @@ -33,7 +33,7 @@ 7F85FB891C9CF7B000CEE132 /* FormURLEncodedDataParserTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7F85FB881C9CF7B000CEE132 /* FormURLEncodedDataParserTests.swift */; }; 7F85FB8E1C9D317300CEE132 /* URLSessionAdapter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7F85FB8C1C9D317300CEE132 /* URLSessionAdapter.swift */; }; 7F85FB8F1C9D317300CEE132 /* SessionAdapterType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7F85FB8D1C9D317300CEE132 /* SessionAdapterType.swift */; }; - 7F85FB921C9D336D00CEE132 /* NSURLSessionAdapterTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7F85FB911C9D336D00CEE132 /* NSURLSessionAdapterTests.swift */; }; + 7F85FB921C9D336D00CEE132 /* URLSessionAdapterTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7F85FB911C9D336D00CEE132 /* URLSessionAdapterTests.swift */; }; 7F85FB9A1C9D3DA700CEE132 /* TestRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7F85FB981C9D3DA700CEE132 /* TestRequest.swift */; }; 7F85FB9B1C9D3DA700CEE132 /* TestSessionAdapter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7F85FB991C9D3DA700CEE132 /* TestSessionAdapter.swift */; }; 7F85FB9F1C9D3F0B00CEE132 /* SessionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7F85FB9E1C9D3F0B00CEE132 /* SessionTests.swift */; }; @@ -93,8 +93,8 @@ 7F18BD101C972C69003A31DF /* JSONBodyParameters.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = JSONBodyParameters.swift; sourceTree = ""; }; 7F18BD121C972E5A003A31DF /* FormURLEncodedBodyParameters.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FormURLEncodedBodyParameters.swift; sourceTree = ""; }; 7F18BD181C9730ED003A31DF /* URLEncodedSerialization.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = URLEncodedSerialization.swift; sourceTree = ""; }; - 7F2001D61CF49F3000C5D0EE /* NSURLSessionAdapterSubclassTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NSURLSessionAdapterSubclassTests.swift; sourceTree = ""; }; - 7F2A15BC1CEB5F67009A12A2 /* NSData+NSInputStream.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "NSData+NSInputStream.swift"; sourceTree = ""; }; + 7F2001D61CF49F3000C5D0EE /* URLSessionAdapterSubclassTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = URLSessionAdapterSubclassTests.swift; sourceTree = ""; }; + 7F2A15BC1CEB5F67009A12A2 /* Data+InputStream.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Data+InputStream.swift"; sourceTree = ""; }; 7F2A53791CF52165000353F0 /* test.json */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.json; path = test.json; sourceTree = ""; }; 7F2A537B1CF5D55D000353F0 /* URLEncodedSerializationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = URLEncodedSerializationTests.swift; sourceTree = ""; }; 7F7E8F0B1C8AD4B1008A13A9 /* APIKit.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = APIKit.h; sourceTree = ""; }; @@ -108,7 +108,7 @@ 7F85FB881C9CF7B000CEE132 /* FormURLEncodedDataParserTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FormURLEncodedDataParserTests.swift; sourceTree = ""; }; 7F85FB8C1C9D317300CEE132 /* URLSessionAdapter.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = URLSessionAdapter.swift; sourceTree = ""; }; 7F85FB8D1C9D317300CEE132 /* SessionAdapterType.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SessionAdapterType.swift; sourceTree = ""; }; - 7F85FB911C9D336D00CEE132 /* NSURLSessionAdapterTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NSURLSessionAdapterTests.swift; sourceTree = ""; }; + 7F85FB911C9D336D00CEE132 /* URLSessionAdapterTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = URLSessionAdapterTests.swift; sourceTree = ""; }; 7F85FB981C9D3DA700CEE132 /* TestRequest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TestRequest.swift; sourceTree = ""; }; 7F85FB991C9D3DA700CEE132 /* TestSessionAdapter.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TestSessionAdapter.swift; sourceTree = ""; }; 7F85FB9E1C9D3F0B00CEE132 /* SessionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SessionTests.swift; sourceTree = ""; }; @@ -203,7 +203,7 @@ 7F18BD101C972C69003A31DF /* JSONBodyParameters.swift */, 7F18BD121C972E5A003A31DF /* FormURLEncodedBodyParameters.swift */, 7FA19A311C98542E005D25AE /* MultipartFormDataBodyParameters.swift */, - 7F2A15BC1CEB5F67009A12A2 /* NSData+NSInputStream.swift */, + 7F2A15BC1CEB5F67009A12A2 /* Data+InputStream.swift */, 7FAC64AC1CDC7ADE00F1BB45 /* AbstractInputStream.m */, ); path = BodyParametersType; @@ -287,8 +287,8 @@ 7F85FB901C9D335F00CEE132 /* SessionAdapterType */ = { isa = PBXGroup; children = ( - 7F85FB911C9D336D00CEE132 /* NSURLSessionAdapterTests.swift */, - 7F2001D61CF49F3000C5D0EE /* NSURLSessionAdapterSubclassTests.swift */, + 7F85FB911C9D336D00CEE132 /* URLSessionAdapterTests.swift */, + 7F2001D61CF49F3000C5D0EE /* URLSessionAdapterSubclassTests.swift */, ); path = SessionAdapterType; sourceTree = ""; @@ -452,7 +452,7 @@ 7FA19A431C9CBF2A005D25AE /* SessionTaskError.swift in Sources */, 7F7E8F1C1C8AD4B1008A13A9 /* Session.swift in Sources */, 7F18BD0F1C972C38003A31DF /* BodyParametersType.swift in Sources */, - 7F2A15BD1CEB5F67009A12A2 /* NSData+NSInputStream.swift in Sources */, + 7F2A15BD1CEB5F67009A12A2 /* Data+InputStream.swift in Sources */, 7FAC40341C8F2C900098C4B2 /* Box.swift in Sources */, 7FB650DF1CEA0E6B00366992 /* StringDataParser.swift in Sources */, 7F18BD131C972E5A003A31DF /* FormURLEncodedBodyParameters.swift in Sources */, @@ -482,11 +482,11 @@ 7FA19A3A1C98642F005D25AE /* FormURLEncodedBodyParametersTests.swift in Sources */, 7F85FB831C9CF25D00CEE132 /* JSONDataParserTests.swift in Sources */, 7F85FB9F1C9D3F0B00CEE132 /* SessionTests.swift in Sources */, - 7F85FB921C9D336D00CEE132 /* NSURLSessionAdapterTests.swift in Sources */, + 7F85FB921C9D336D00CEE132 /* URLSessionAdapterTests.swift in Sources */, 7F2A537C1CF5D55D000353F0 /* URLEncodedSerializationTests.swift in Sources */, 7F09BF931C8AE8DB00F4A59A /* RequestTypeTests.swift in Sources */, 7FA19A3B1C98642F005D25AE /* JSONBodyParametersTests.swift in Sources */, - 7F2001D71CF49F3000C5D0EE /* NSURLSessionAdapterSubclassTests.swift in Sources */, + 7F2001D71CF49F3000C5D0EE /* URLSessionAdapterSubclassTests.swift in Sources */, 7F85FB9A1C9D3DA700CEE132 /* TestRequest.swift in Sources */, 7F85FB9B1C9D3DA700CEE132 /* TestSessionAdapter.swift in Sources */, ); diff --git a/Sources/BodyParametersType/NSData+NSInputStream.swift b/Sources/BodyParametersType/Data+InputStream.swift similarity index 100% rename from Sources/BodyParametersType/NSData+NSInputStream.swift rename to Sources/BodyParametersType/Data+InputStream.swift diff --git a/Tests/APIKit/SessionAdapterType/NSURLSessionAdapterSubclassTests.swift b/Tests/APIKit/SessionAdapterType/URLSessionAdapterSubclassTests.swift similarity index 100% rename from Tests/APIKit/SessionAdapterType/NSURLSessionAdapterSubclassTests.swift rename to Tests/APIKit/SessionAdapterType/URLSessionAdapterSubclassTests.swift diff --git a/Tests/APIKit/SessionAdapterType/NSURLSessionAdapterTests.swift b/Tests/APIKit/SessionAdapterType/URLSessionAdapterTests.swift similarity index 100% rename from Tests/APIKit/SessionAdapterType/NSURLSessionAdapterTests.swift rename to Tests/APIKit/SessionAdapterType/URLSessionAdapterTests.swift From ac3aa7d218ce366598bd046b815dfc9b4a8077f2 Mon Sep 17 00:00:00 2001 From: Syo Ikeda Date: Fri, 19 Aug 2016 01:08:39 +0900 Subject: [PATCH 16/38] Update to Xcode 8 beta 6 --- Cartfile | 2 +- Cartfile.resolved | 2 +- Carthage/Checkouts/Result | 2 +- .../FormURLEncodedBodyParameters.swift | 4 ++-- .../JSONBodyParameters.swift | 4 ++-- .../MultipartFormDataBodyParameters.swift | 4 ++-- Sources/CallbackQueue.swift | 2 +- Sources/DataParserType/DataParserType.swift | 4 ++-- .../FormURLEncodedDataParser.swift | 6 +++--- Sources/DataParserType/JSONDataParser.swift | 6 +++--- Sources/DataParserType/StringDataParser.swift | 2 +- Sources/Error/ResponseError.swift | 6 +++--- Sources/RequestType.swift | 20 +++++++++---------- .../URLEncodedSerialization.swift | 10 +++++----- Sources/Session.swift | 12 +++++------ .../SessionAdapterType.swift | 4 ++-- .../URLSessionAdapter.swift | 18 ++++++++--------- .../JSONBodyParametersTests.swift | 6 +++--- .../MultipartFormDataParametersTests.swift | 2 +- .../URLEncodedSerializationTests.swift | 10 +++++----- Tests/APIKit/RequestTypeTests.swift | 8 ++++---- .../URLSessionAdapterTests.swift | 2 +- Tests/APIKit/SessionTests.swift | 8 ++++---- Tests/APIKit/TestComponents/TestRequest.swift | 8 ++++---- .../TestComponents/TestSessionAdapter.swift | 6 +++--- .../TestComponents/TestSessionTask.swift | 2 +- 26 files changed, 80 insertions(+), 80 deletions(-) diff --git a/Cartfile b/Cartfile index 4868aaec..32737a64 100644 --- a/Cartfile +++ b/Cartfile @@ -1 +1 @@ -github "antitypical/Result" "3.0.0-alpha.2" +github "antitypical/Result" "3.0.0-alpha.3" diff --git a/Cartfile.resolved b/Cartfile.resolved index da6b78b8..e0ee8dc0 100644 --- a/Cartfile.resolved +++ b/Cartfile.resolved @@ -1,2 +1,2 @@ github "ikesyo/OHHTTPStubs" "a2e8edf5fc75adc80bd17743a07b262d3f3063b3" -github "antitypical/Result" "3.0.0-alpha.2" +github "antitypical/Result" "3.0.0-alpha.3" diff --git a/Carthage/Checkouts/Result b/Carthage/Checkouts/Result index 03eb2c27..d78cac38 160000 --- a/Carthage/Checkouts/Result +++ b/Carthage/Checkouts/Result @@ -1 +1 @@ -Subproject commit 03eb2c274eb3cab2b2bd4b25586b3d6325607e2c +Subproject commit d78cac38657de99d85f8f1770b290d039721ef27 diff --git a/Sources/BodyParametersType/FormURLEncodedBodyParameters.swift b/Sources/BodyParametersType/FormURLEncodedBodyParameters.swift index 649e856f..52ba3332 100644 --- a/Sources/BodyParametersType/FormURLEncodedBodyParameters.swift +++ b/Sources/BodyParametersType/FormURLEncodedBodyParameters.swift @@ -3,13 +3,13 @@ import Foundation /// `FormURLEncodedBodyParameters` serializes form object for HTTP body and states its content type is form. public struct FormURLEncodedBodyParameters: BodyParametersType { /// The form object to be serialized. - public let form: [String: AnyObject] + public let form: [String: Any] /// The string encoding of the serialized form. public let encoding: String.Encoding /// Returns `FormURLEncodedBodyParameters` that is initialized with form object and encoding. - public init(formObject: [String: AnyObject], encoding: String.Encoding = .utf8) { + public init(formObject: [String: Any], encoding: String.Encoding = .utf8) { self.form = formObject self.encoding = encoding } diff --git a/Sources/BodyParametersType/JSONBodyParameters.swift b/Sources/BodyParametersType/JSONBodyParameters.swift index f793e9f9..30c84ae0 100644 --- a/Sources/BodyParametersType/JSONBodyParameters.swift +++ b/Sources/BodyParametersType/JSONBodyParameters.swift @@ -3,13 +3,13 @@ import Foundation /// `JSONBodyParameters` serializes JSON object for HTTP body and states its content type is JSON. public struct JSONBodyParameters: BodyParametersType { /// The JSON object to be serialized. - public let JSONObject: AnyObject + public let JSONObject: Any /// The writing options for serialization. public let writingOptions: JSONSerialization.WritingOptions /// Returns `JSONBodyParameters` that is initialized with JSON object and writing options. - public init(JSONObject: AnyObject, writingOptions: JSONSerialization.WritingOptions = []) { + public init(JSONObject: Any, writingOptions: JSONSerialization.WritingOptions = []) { self.JSONObject = JSONObject self.writingOptions = writingOptions } diff --git a/Sources/BodyParametersType/MultipartFormDataBodyParameters.swift b/Sources/BodyParametersType/MultipartFormDataBodyParameters.swift index f8541cbd..6ac3bfca 100644 --- a/Sources/BodyParametersType/MultipartFormDataBodyParameters.swift +++ b/Sources/BodyParametersType/MultipartFormDataBodyParameters.swift @@ -67,7 +67,7 @@ public extension MultipartFormDataBodyParameters { /// `value` will be converted via `String(_:)` and serialized via `String.dataUsingEncoding(_:)`. /// If `mimeType` or `fileName` are `nil`, the fields will be omitted. public init(value: Any, name: String, mimeType: String? = nil, fileName: String? = nil, encoding: String.Encoding = .utf8) throws { - guard let data = String(value).data(using: encoding) else { + guard let data = String(describing: value).data(using: encoding) else { throw Error.IllegalValue(value) } @@ -103,7 +103,7 @@ public extension MultipartFormDataBodyParameters { throw Error.CannotGetFileSize(fileUrl) } - let detectedMimeType = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, fileUrl.pathExtension, nil) + let detectedMimeType = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, fileUrl.pathExtension as CFString, nil) .map { $0.takeRetainedValue() } .flatMap { UTTypeCopyPreferredTagWithClass($0, kUTTagClassMIMEType)?.takeRetainedValue() } .map { $0 as String } diff --git a/Sources/CallbackQueue.swift b/Sources/CallbackQueue.swift index 6964122f..540b835c 100644 --- a/Sources/CallbackQueue.swift +++ b/Sources/CallbackQueue.swift @@ -14,7 +14,7 @@ public enum CallbackQueue { /// Dispatches callback closure on associated dispatch queue. case DispatchQueue(Foundation.DispatchQueue) - internal func execute(closure: () -> Void) { + internal func execute(closure: @escaping () -> Void) { switch self { case .Main: Foundation.DispatchQueue.main.async { diff --git a/Sources/DataParserType/DataParserType.swift b/Sources/DataParserType/DataParserType.swift index 4ee059d8..8806958a 100644 --- a/Sources/DataParserType/DataParserType.swift +++ b/Sources/DataParserType/DataParserType.swift @@ -5,7 +5,7 @@ public protocol DataParserType { /// Value for `Accept` header field of HTTP request. var contentType: String? { get } - /// Return `AnyObject` that expresses structure of response such as JSON and XML. + /// Return `Any` that expresses structure of response such as JSON and XML. /// - Throws: `ErrorType` when parser encountered invalid format data. - func parseData(_ data: Data) throws -> AnyObject + func parseData(_ data: Data) throws -> Any } diff --git a/Sources/DataParserType/FormURLEncodedDataParser.swift b/Sources/DataParserType/FormURLEncodedDataParser.swift index e032868f..273c510b 100644 --- a/Sources/DataParserType/FormURLEncodedDataParser.swift +++ b/Sources/DataParserType/FormURLEncodedDataParser.swift @@ -21,9 +21,9 @@ public class FormURLEncodedDataParser: DataParserType { return "application/x-www-form-urlencoded" } - /// Return `AnyObject` that expresses structure of response. + /// Return `Any` that expresses structure of response. /// - Throws: `FormURLEncodedDataParser.Error` when the parser fails to initialize `String` from `Data`. - public func parseData(_ data: Data) throws -> AnyObject { + public func parseData(_ data: Data) throws -> Any { guard let string = String(data: data, encoding: encoding) else { throw Error.CannotGetStringFromData(data) } @@ -32,7 +32,7 @@ public class FormURLEncodedDataParser: DataParserType { components.percentEncodedQuery = string let queryItems = components.queryItems ?? [] - var dictionary = [String: AnyObject]() + var dictionary = [String: Any]() for queryItem in queryItems { dictionary[queryItem.name] = queryItem.value diff --git a/Sources/DataParserType/JSONDataParser.swift b/Sources/DataParserType/JSONDataParser.swift index c64d1757..62e75990 100644 --- a/Sources/DataParserType/JSONDataParser.swift +++ b/Sources/DataParserType/JSONDataParser.swift @@ -17,9 +17,9 @@ public class JSONDataParser: DataParserType { return "application/json" } - /// Return `AnyObject` that expresses structure of JSON response. - /// - Throws: `NSError` when `JSONSerialization` fails to deserialize `Data` into `AnyObject`. - public func parseData(_ data: Data) throws -> AnyObject { + /// Return `Any` that expresses structure of JSON response. + /// - Throws: `NSError` when `JSONSerialization` fails to deserialize `Data` into `Any`. + public func parseData(_ data: Data) throws -> Any { guard data.count > 0 else { return [:] } diff --git a/Sources/DataParserType/StringDataParser.swift b/Sources/DataParserType/StringDataParser.swift index 36956927..d8d363e1 100644 --- a/Sources/DataParserType/StringDataParser.swift +++ b/Sources/DataParserType/StringDataParser.swift @@ -23,7 +23,7 @@ public class StringDataParser: DataParserType { /// Return `String` that converted from `Data`. /// - Throws: `StringDataParser.Error` when the parser fails to initialize `String` from `Data`. - public func parseData(_ data: Data) throws -> AnyObject { + public func parseData(_ data: Data) throws -> Any { guard let string = String(data: data, encoding: encoding) else { throw Error.InvalidData(data) } diff --git a/Sources/Error/ResponseError.swift b/Sources/Error/ResponseError.swift index cd061611..d5b59ad8 100644 --- a/Sources/Error/ResponseError.swift +++ b/Sources/Error/ResponseError.swift @@ -1,7 +1,7 @@ import Foundation /// `ResponseError` represents a common error that occurs while getting `RequestType.Response` -/// from raw result tuple `(Data?, URLResponse?, NSError?)`. +/// from raw result tuple `(NSData?, URLResponse?, Error?)`. public enum ResponseError: Error { /// Indicates the session adapter returned `URLResponse` that fails to down-cast to `HTTPURLResponse`. case NonHTTPURLResponse(URLResponse?) @@ -10,6 +10,6 @@ public enum ResponseError: Error { /// In most cases, *acceptable* means the value is in `200..<300`. case UnacceptableStatusCode(Int) - /// Indicates `AnyObject` that represents the response is unexpected. - case UnexpectedObject(AnyObject) + /// Indicates `Any` that represents the response is unexpected. + case UnexpectedObject(Any) } diff --git a/Sources/RequestType.swift b/Sources/RequestType.swift index b2c321db..b6e57f6b 100644 --- a/Sources/RequestType.swift +++ b/Sources/RequestType.swift @@ -7,7 +7,7 @@ import Result /// - `var baseUrl: URL` /// - `var method: HTTPMethod` /// - `var path: String` -/// - `func responseFromObject(object: AnyObject, urlResponse: HTTPURLResponse) throws -> Response` +/// - `func responseFromObject(object: Any, urlResponse: HTTPURLResponse) throws -> Response` public protocol RequestType { /// The response type associated with the request type. associatedtype Response @@ -24,12 +24,12 @@ public protocol RequestType { /// The convenience property for `queryParameters` and `bodyParameters`. If the implementation of /// `queryParameters` and `bodyParameters` are not provided, the values for them will be computed /// from this property depending on `method`. - var parameters: AnyObject? { get } + var parameters: Any? { get } /// The actual parameters for the URL query. The values of this property will be escaped using `URLEncodedSerialization`. /// If this property is not implemented and `method.prefersQueryParameter` is `true`, the value of this property /// will be computed from `parameters`. - var queryParameters: [String: AnyObject]? { get } + var queryParameters: [String: Any]? { get } /// The actual parameters for the HTTP body. If this property is not implemented and `method.prefersQueryParameter` is `false`, /// the value of this property will be computed from `parameters` using `JSONBodyParameters`. @@ -48,26 +48,26 @@ public protocol RequestType { /// - Throws: `ErrorType` func interceptURLRequest(_ urlRequest: URLRequest) throws -> URLRequest - /// Intercepts response `AnyObject` and `HTTPURLResponse`. If an error is thrown in this method, + /// Intercepts response `Any` and `HTTPURLResponse`. If an error is thrown in this method, /// the result of `Session.sendRequest()` turns `.failure(.ResponseError(error))`. /// The default implementation of this method is provided to throw `RequestError.UnacceptableStatusCode` /// if the HTTP status code is not in `200..<300`. /// - Throws: `ErrorType` - func interceptObject(_ object: AnyObject, urlResponse: HTTPURLResponse) throws -> AnyObject + func interceptObject(_ object: Any, urlResponse: HTTPURLResponse) throws -> Any /// Build `Response` instance from raw response object. This method is called after /// `interceptObject(:URLResponse:)` if it does not throw any error. /// - Throws: `ErrorType` - func responseFromObject(_ object: AnyObject, urlResponse: HTTPURLResponse) throws -> Response + func responseFromObject(_ object: Any, urlResponse: HTTPURLResponse) throws -> Response } public extension RequestType { - public var parameters: AnyObject? { + public var parameters: Any? { return nil } - public var queryParameters: [String: AnyObject]? { - guard let parameters = parameters as? [String: AnyObject], method.prefersQueryParameters else { + public var queryParameters: [String: Any]? { + guard let parameters = parameters as? [String: Any], method.prefersQueryParameters else { return nil } @@ -94,7 +94,7 @@ public extension RequestType { return urlRequest } - public func interceptObject(_ object: AnyObject, urlResponse: HTTPURLResponse) throws -> AnyObject { + public func interceptObject(_ object: Any, urlResponse: HTTPURLResponse) throws -> Any { guard (200..<300).contains(urlResponse.statusCode) else { throw ResponseError.UnacceptableStatusCode(urlResponse.statusCode) } diff --git a/Sources/Serializations/URLEncodedSerialization.swift b/Sources/Serializations/URLEncodedSerialization.swift index ed9f59e9..0f6f70cb 100644 --- a/Sources/Serializations/URLEncodedSerialization.swift +++ b/Sources/Serializations/URLEncodedSerialization.swift @@ -38,7 +38,7 @@ private func escape(_ string: String) -> String { } private func unescape(_ string: String) -> String { - return CFURLCreateStringByReplacingPercentEscapes(nil, string, nil) as String + return CFURLCreateStringByReplacingPercentEscapes(nil, string as CFString, nil) as String } /// `URLEncodedSerialization` parses `Data` and `String` as urlencoded, @@ -47,7 +47,7 @@ public final class URLEncodedSerialization { public enum Error: Swift.Error { case CannotGetStringFromData(Data, String.Encoding) case CannotGetDataFromString(String, String.Encoding) - case CannotCastObjectToDictionary(AnyObject) + case CannotCastObjectToDictionary(Any) case InvalidFormatString(String) } @@ -74,8 +74,8 @@ public final class URLEncodedSerialization { /// Returns urlencoded `Data` from the object. /// - Throws: URLEncodedSerialization.Error - public static func dataFromObject(_ object: AnyObject, encoding: String.Encoding) throws -> Data { - guard let dictionary = object as? [String: AnyObject] else { + public static func dataFromObject(_ object: Any, encoding: String.Encoding) throws -> Data { + guard let dictionary = object as? [String: Any] else { throw Error.CannotCastObjectToDictionary(object) } @@ -88,7 +88,7 @@ public final class URLEncodedSerialization { } /// Returns urlencoded `Data` from the string. - public static func stringFromDictionary(_ dictionary: [String: AnyObject]) -> String { + public static func stringFromDictionary(_ dictionary: [String: Any]) -> String { let pairs = dictionary.map { key, value -> String in if value is NSNull { return "\(escape(key))" diff --git a/Sources/Session.swift b/Sources/Session.swift index 7f689f75..c44fc3f2 100644 --- a/Sources/Session.swift +++ b/Sources/Session.swift @@ -4,7 +4,7 @@ import Result private var taskRequestKey = 0 /// `Session` manages tasks for HTTP/HTTPS requests. -public class Session { +open class Session { /// The adapter that connects `Session` instance and lower level backend. public let adapter: SessionAdapterType @@ -27,7 +27,7 @@ public class Session { }() /// The shared `Session` instance for class methods, `Session.sendRequest(_:handler:)` and `Session.cancelRequest(_:passingTest:)`. - public class var sharedSession: Session { + open class var sharedSession: Session { return privateSharedSession } @@ -37,12 +37,12 @@ public class Session { /// - parameter handler: The closure that receives result of the request. /// - returns: The new session task. @discardableResult - public class func sendRequest(_ request: Request, callbackQueue: CallbackQueue? = nil, handler: (Result) -> Void = { _ in }) -> SessionTaskType? { + open class func sendRequest(_ request: Request, callbackQueue: CallbackQueue? = nil, handler: @escaping (Result) -> Void = { _ in }) -> SessionTaskType? { return sharedSession.sendRequest(request, callbackQueue: callbackQueue, handler: handler) } /// Calls `cancelRequest(_:passingTest:)` of `sharedSession`. - public class func cancelRequest(_ requestType: Request.Type, passingTest test: (Request) -> Bool = { _ in true }) { + open class func cancelRequest(_ requestType: Request.Type, passingTest test: @escaping (Request) -> Bool = { _ in true }) { sharedSession.cancelRequest(requestType, passingTest: test) } @@ -55,7 +55,7 @@ public class Session { /// - parameter handler: The closure that receives result of the request. /// - returns: The new session task. @discardableResult - public func sendRequest(_ request: Request, callbackQueue: CallbackQueue? = nil, handler: (Result) -> Void = { _ in }) -> SessionTaskType? { + open func sendRequest(_ request: Request, callbackQueue: CallbackQueue? = nil, handler: @escaping (Result) -> Void = { _ in }) -> SessionTaskType? { let callbackQueue = callbackQueue ?? self.callbackQueue let urlRequest: URLRequest @@ -100,7 +100,7 @@ public class Session { /// Cancels requests that passes the test. /// - parameter requestType: The request type to cancel. /// - parameter test: The test closure that determines if a request should be cancelled or not. - public func cancelRequest(_ requestType: Request.Type, passingTest test: (Request) -> Bool = { _ in true }) { + open func cancelRequest(_ requestType: Request.Type, passingTest test: @escaping (Request) -> Bool = { _ in true }) { adapter.getTasksWithHandler { [weak self] tasks in return tasks .filter { task in diff --git a/Sources/SessionAdapterType/SessionAdapterType.swift b/Sources/SessionAdapterType/SessionAdapterType.swift index a9920a50..ae4325ba 100644 --- a/Sources/SessionAdapterType/SessionAdapterType.swift +++ b/Sources/SessionAdapterType/SessionAdapterType.swift @@ -11,8 +11,8 @@ public protocol SessionTaskType: class { /// with `Session`. public protocol SessionAdapterType { /// Returns instance that conforms to `SessionTaskType`. `handler` must be called after success or failure. - func createTaskWithURLRequest(_ URLRequest: URLRequest, handler: (NSData?, URLResponse?, Error?) -> Void) -> SessionTaskType + func createTaskWithURLRequest(_ URLRequest: URLRequest, handler: @escaping (NSData?, URLResponse?, Error?) -> Void) -> SessionTaskType /// Collects tasks from backend networking stack. `handler` must be called after collecting. - func getTasksWithHandler(_ handler: ([SessionTaskType]) -> Void) + func getTasksWithHandler(_ handler: @escaping ([SessionTaskType]) -> Void) } diff --git a/Sources/SessionAdapterType/URLSessionAdapter.swift b/Sources/SessionAdapterType/URLSessionAdapter.swift index 249c941e..dcac7072 100644 --- a/Sources/SessionAdapterType/URLSessionAdapter.swift +++ b/Sources/SessionAdapterType/URLSessionAdapter.swift @@ -14,9 +14,9 @@ private var taskAssociatedObjectCompletionHandlerKey = 0 /// delegate methods that you want to implement. Since `URLSessionAdapter` also implements delegate methods /// `URLSession(_:task: didCompleteWithError:)` and `URLSession(_:dataTask:didReceiveData:)`, you have to call /// `super` in these methods if you implement them. -public class URLSessionAdapter: NSObject, SessionAdapterType, URLSessionDelegate, URLSessionTaskDelegate, URLSessionDataDelegate { +open class URLSessionAdapter: NSObject, SessionAdapterType, URLSessionDelegate, URLSessionTaskDelegate, URLSessionDataDelegate { /// The undelying `URLSession` instance. - public var urlSession: URLSession! + open var urlSession: URLSession! /// Returns `URLSessionAdapter` initialized with `URLSessionConfiguration`. public init(configuration: URLSessionConfiguration) { @@ -25,7 +25,7 @@ public class URLSessionAdapter: NSObject, SessionAdapterType, URLSessionDelegate } /// Creates `URLSessionDataTask` instance using `dataTaskWithRequest(_:completionHandler:)`. - public func createTaskWithURLRequest(_ URLRequest: URLRequest, handler: (NSData?, URLResponse?, Error?) -> Void) -> SessionTaskType { + open func createTaskWithURLRequest(_ URLRequest: URLRequest, handler: @escaping (NSData?, URLResponse?, Error?) -> Void) -> SessionTaskType { let task = urlSession.dataTask(with: URLRequest) setBuffer(NSMutableData(), forTask: task) @@ -37,7 +37,7 @@ public class URLSessionAdapter: NSObject, SessionAdapterType, URLSessionDelegate } /// Aggregates `URLSessionTask` instances in `URLSession` using `getTasksWithCompletionHandler(_:)`. - public func getTasksWithHandler(_ handler: ([SessionTaskType]) -> Void) { + open func getTasksWithHandler(_ handler: @escaping ([SessionTaskType]) -> Void) { urlSession.getTasksWithCompletionHandler { dataTasks, uploadTasks, downloadTasks in let allTasks = dataTasks as [URLSessionTask] + uploadTasks as [URLSessionTask] @@ -55,21 +55,21 @@ public class URLSessionAdapter: NSObject, SessionAdapterType, URLSessionDelegate return objc_getAssociatedObject(task, &dataTaskResponseBufferKey) as? NSMutableData } - private func setHandler(_ handler: (NSData?, URLResponse?, NSError?) -> Void, forTask task: URLSessionTask) { + private func setHandler(_ handler: (NSData?, URLResponse?, Error?) -> Void, forTask task: URLSessionTask) { objc_setAssociatedObject(task, &taskAssociatedObjectCompletionHandlerKey, Box(handler), .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } - private func handlerForTask(_ task: URLSessionTask) -> ((NSData?, URLResponse?, NSError?) -> Void)? { - return (objc_getAssociatedObject(task, &taskAssociatedObjectCompletionHandlerKey) as? Box<(NSData?, URLResponse?, NSError?) -> Void>)?.value + private func handlerForTask(_ task: URLSessionTask) -> ((NSData?, URLResponse?, Error?) -> Void)? { + return (objc_getAssociatedObject(task, &taskAssociatedObjectCompletionHandlerKey) as? Box<(NSData?, URLResponse?, Error?) -> Void>)?.value } // MARK: URLSessionTaskDelegate - public func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { + open func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { handlerForTask(task)?(bufferForTask(task), task.response, error) } // MARK: URLSessionDataDelegate - public func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) { + open func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) { bufferForTask(dataTask)?.append(data) } } diff --git a/Tests/APIKit/BodyParametersType/JSONBodyParametersTests.swift b/Tests/APIKit/BodyParametersType/JSONBodyParametersTests.swift index 4bae4d46..100ae810 100644 --- a/Tests/APIKit/BodyParametersType/JSONBodyParametersTests.swift +++ b/Tests/APIKit/BodyParametersType/JSONBodyParametersTests.swift @@ -15,9 +15,9 @@ class JSONBodyParametersTests: XCTestCase { } let dictionary = try JSONSerialization.jsonObject(with: data, options: []) - XCTAssertEqual(dictionary["foo"], 1) - XCTAssertEqual(dictionary["bar"], 2) - XCTAssertEqual(dictionary["baz"], 3) + XCTAssertEqual((dictionary as? [String: Int])?["foo"], 1) + XCTAssertEqual((dictionary as? [String: Int])?["bar"], 2) + XCTAssertEqual((dictionary as? [String: Int])?["baz"], 3) } catch { XCTFail() } diff --git a/Tests/APIKit/BodyParametersType/MultipartFormDataParametersTests.swift b/Tests/APIKit/BodyParametersType/MultipartFormDataParametersTests.swift index 94f61a22..77998290 100644 --- a/Tests/APIKit/BodyParametersType/MultipartFormDataParametersTests.swift +++ b/Tests/APIKit/BodyParametersType/MultipartFormDataParametersTests.swift @@ -71,7 +71,7 @@ class MultipartFormDataParametersTests: XCTestCase { // MARK: Values func testFileValue() { - let fileUrl = Bundle(for: self.dynamicType).url(forResource: "test", withExtension: "json")! + let fileUrl = Bundle(for: type(of: self)).url(forResource: "test", withExtension: "json")! let part = try! MultipartFormDataBodyParameters.Part(fileUrl: fileUrl, name: "test") let parameters = MultipartFormDataBodyParameters(parts: [part]) diff --git a/Tests/APIKit/BodyParametersType/URLEncodedSerializationTests.swift b/Tests/APIKit/BodyParametersType/URLEncodedSerializationTests.swift index 92bb272f..7d81fef8 100644 --- a/Tests/APIKit/BodyParametersType/URLEncodedSerializationTests.swift +++ b/Tests/APIKit/BodyParametersType/URLEncodedSerializationTests.swift @@ -3,7 +3,7 @@ import XCTest import APIKit class URLEncodedSerializationTests: XCTestCase { - // MARK: NSData -> AnyObject + // MARK: NSData -> Any func testObjectFromData() { let data = "key1=value1&key2=value2".data(using: .utf8)! let object = try? URLEncodedSerialization.objectFromData(data, encoding: .utf8) @@ -48,16 +48,16 @@ class URLEncodedSerializationTests: XCTestCase { } } - // MARK: AnyObject -> NSData + // MARK: Any -> NSData func testDataFromObject() { - let object = ["hey": "yo"] as AnyObject + let object = ["hey": "yo"] as Any let data = try? URLEncodedSerialization.dataFromObject(object, encoding: .utf8) let string = data.flatMap { String(data: $0, encoding: .utf8) } XCTAssertEqual(string, "hey=yo") } func testNonDictionaryObject() { - let dictionaries = [["hey": "yo"]] as AnyObject + let dictionaries = [["hey": "yo"]] as Any do { try _ = URLEncodedSerialization.dataFromObject(dictionaries, encoding: .utf8) @@ -69,7 +69,7 @@ class URLEncodedSerializationTests: XCTestCase { return } - XCTAssertEqual(object["hey"], dictionaries["hey"]) + XCTAssertEqual((object as AnyObject)["hey"], (dictionaries as AnyObject)["hey"]) } } } diff --git a/Tests/APIKit/RequestTypeTests.swift b/Tests/APIKit/RequestTypeTests.swift index bc4c4c30..c5fae65b 100644 --- a/Tests/APIKit/RequestTypeTests.swift +++ b/Tests/APIKit/RequestTypeTests.swift @@ -29,22 +29,22 @@ class RequestTypeTests: XCTestCase { } func testPOSTJSONRequest() { - let parameters: [AnyObject] = [ + let parameters: [Any] = [ ["id": "1"], ["id": "2"], ["hello", "yellow"] ] let request = TestRequest(method: .POST, parameters: parameters) - XCTAssert(request.parameters?.count == 3) + XCTAssert((request.parameters as? [Any])?.count == 3) let urlRequest = try? request.buildURLRequest() XCTAssertNotNil(urlRequest?.httpBody) let json = urlRequest?.httpBody.flatMap { try? JSONSerialization.jsonObject(with: $0, options: []) } as? [AnyObject] XCTAssertEqual(json?.count, 3) - XCTAssertEqual(json?[0]["id"], "1") - XCTAssertEqual(json?[1]["id"], "2") + XCTAssertEqual((json?[0] as? [String: String])?["id"], "1") + XCTAssertEqual((json?[1] as? [String: String])?["id"], "2") let array = json?[2] as? [String] XCTAssertEqual(array?[0], "hello") diff --git a/Tests/APIKit/SessionAdapterType/URLSessionAdapterTests.swift b/Tests/APIKit/SessionAdapterType/URLSessionAdapterTests.swift index 6e3d0c68..e29b2439 100644 --- a/Tests/APIKit/SessionAdapterType/URLSessionAdapterTests.swift +++ b/Tests/APIKit/SessionAdapterType/URLSessionAdapterTests.swift @@ -36,7 +36,7 @@ class URLSessionAdapterTests: XCTestCase { session.sendRequest(request) { response in switch response { case .success(let dictionary): - XCTAssertEqual(dictionary["key"], "value") + XCTAssertEqual((dictionary as? [String: String])?["key"], "value") case .failure: XCTFail() diff --git a/Tests/APIKit/SessionTests.swift b/Tests/APIKit/SessionTests.swift index 2513ffb0..804cdfce 100644 --- a/Tests/APIKit/SessionTests.swift +++ b/Tests/APIKit/SessionTests.swift @@ -25,7 +25,7 @@ class SessionTests: XCTestCase { session.sendRequest(request) { response in switch response { case .success(let dictionary): - XCTAssertEqual(dictionary["key"], "value") + XCTAssertEqual((dictionary as? [String: String])?["key"], "value") case .failure: XCTFail() @@ -191,7 +191,7 @@ class SessionTests: XCTestCase { return "/" } - func responseFromObject(_ object: AnyObject, urlResponse: HTTPURLResponse) throws -> Response { + func responseFromObject(_ object: Any, urlResponse: HTTPURLResponse) throws -> Response { return () } } @@ -239,12 +239,12 @@ class SessionTests: XCTestCase { return testSesssion } - private override func sendRequest(_ request: Request, callbackQueue: CallbackQueue?, handler: (Result) -> Void) -> SessionTaskType? { + private override func sendRequest(_ request: Request, callbackQueue: CallbackQueue?, handler: @escaping (Result) -> Void) -> SessionTaskType? { functionCallFlags[(#function)] = true return super.sendRequest(request) } - private override func cancelRequest(_ requestType: Request.Type, passingTest test: (Request) -> Bool) { + private override func cancelRequest(_ requestType: Request.Type, passingTest test: @escaping (Request) -> Bool) { functionCallFlags[(#function)] = true } } diff --git a/Tests/APIKit/TestComponents/TestRequest.swift b/Tests/APIKit/TestComponents/TestRequest.swift index 142efe3a..a3f98192 100644 --- a/Tests/APIKit/TestComponents/TestRequest.swift +++ b/Tests/APIKit/TestComponents/TestRequest.swift @@ -8,9 +8,9 @@ struct TestRequest: RequestType { } // MARK: RequestType - typealias Response = AnyObject + typealias Response = Any - init(baseUrl: String = "https://example.com", path: String = "/", method: HTTPMethod = .GET, parameters: AnyObject? = [:], headerFields: [String: String] = [:], interceptURLRequest: (URLRequest) throws -> URLRequest = { $0 }) { + init(baseUrl: String = "https://example.com", path: String = "/", method: HTTPMethod = .GET, parameters: Any? = [:], headerFields: [String: String] = [:], interceptURLRequest: @escaping (URLRequest) throws -> URLRequest = { $0 }) { self.baseUrl = URL(string: baseUrl)! self.path = path self.method = method @@ -22,7 +22,7 @@ struct TestRequest: RequestType { let baseUrl: URL let method: HTTPMethod let path: String - let parameters: AnyObject? + let parameters: Any? let headerFields: [String: String] let interceptURLRequest: (URLRequest) throws -> URLRequest @@ -30,7 +30,7 @@ struct TestRequest: RequestType { return try interceptURLRequest(urlRequest) } - func responseFromObject(_ object: AnyObject, urlResponse: HTTPURLResponse) throws -> Response { + func responseFromObject(_ object: Any, urlResponse: HTTPURLResponse) throws -> Response { return object } } diff --git a/Tests/APIKit/TestComponents/TestSessionAdapter.swift b/Tests/APIKit/TestComponents/TestSessionAdapter.swift index 89c2cfb1..fe03c722 100644 --- a/Tests/APIKit/TestComponents/TestSessionAdapter.swift +++ b/Tests/APIKit/TestComponents/TestSessionAdapter.swift @@ -42,21 +42,21 @@ class TestSessionAdapter: SessionAdapterType { if task.cancelled { task.handler(nil, nil, Error.cancelled) } else { - task.handler(data, urlResponse, error) + task.handler(data as NSData?, urlResponse, error) } } tasks = [] } - func createTaskWithURLRequest(_ URLRequest: URLRequest, handler: (NSData?, URLResponse?, Swift.Error?) -> Void) -> SessionTaskType { + func createTaskWithURLRequest(_ URLRequest: URLRequest, handler: @escaping (NSData?, URLResponse?, Swift.Error?) -> Void) -> SessionTaskType { let task = TestSessionTask(handler: handler) tasks.append(task) return task } - func getTasksWithHandler(_ handler: ([SessionTaskType]) -> Void) { + func getTasksWithHandler(_ handler: @escaping ([SessionTaskType]) -> Void) { handler(tasks.map { $0 }) } } diff --git a/Tests/APIKit/TestComponents/TestSessionTask.swift b/Tests/APIKit/TestComponents/TestSessionTask.swift index abbdbea1..6e62f1c8 100644 --- a/Tests/APIKit/TestComponents/TestSessionTask.swift +++ b/Tests/APIKit/TestComponents/TestSessionTask.swift @@ -6,7 +6,7 @@ class TestSessionTask: SessionTaskType { var handler: (NSData?, URLResponse?, Error?) -> Void var cancelled = false - init(handler: (NSData?, URLResponse?, Error?) -> Void) { + init(handler: @escaping (NSData?, URLResponse?, Error?) -> Void) { self.handler = handler } From abb9556e668c94adcbf5f3bc29c98901bb4de7ed Mon Sep 17 00:00:00 2001 From: Syo Ikeda Date: Fri, 19 Aug 2016 01:32:36 +0900 Subject: [PATCH 17/38] Use Data instead of NSData --- Sources/Error/ResponseError.swift | 2 +- Sources/SessionAdapterType/SessionAdapterType.swift | 2 +- Sources/SessionAdapterType/URLSessionAdapter.swift | 10 +++++----- Tests/APIKit/TestComponents/TestSessionAdapter.swift | 4 ++-- Tests/APIKit/TestComponents/TestSessionTask.swift | 4 ++-- 5 files changed, 11 insertions(+), 11 deletions(-) diff --git a/Sources/Error/ResponseError.swift b/Sources/Error/ResponseError.swift index d5b59ad8..d8dde149 100644 --- a/Sources/Error/ResponseError.swift +++ b/Sources/Error/ResponseError.swift @@ -1,7 +1,7 @@ import Foundation /// `ResponseError` represents a common error that occurs while getting `RequestType.Response` -/// from raw result tuple `(NSData?, URLResponse?, Error?)`. +/// from raw result tuple `(Data?, URLResponse?, Error?)`. public enum ResponseError: Error { /// Indicates the session adapter returned `URLResponse` that fails to down-cast to `HTTPURLResponse`. case NonHTTPURLResponse(URLResponse?) diff --git a/Sources/SessionAdapterType/SessionAdapterType.swift b/Sources/SessionAdapterType/SessionAdapterType.swift index ae4325ba..06b55b36 100644 --- a/Sources/SessionAdapterType/SessionAdapterType.swift +++ b/Sources/SessionAdapterType/SessionAdapterType.swift @@ -11,7 +11,7 @@ public protocol SessionTaskType: class { /// with `Session`. public protocol SessionAdapterType { /// Returns instance that conforms to `SessionTaskType`. `handler` must be called after success or failure. - func createTaskWithURLRequest(_ URLRequest: URLRequest, handler: @escaping (NSData?, URLResponse?, Error?) -> Void) -> SessionTaskType + func createTaskWithURLRequest(_ URLRequest: URLRequest, handler: @escaping (Data?, URLResponse?, Error?) -> Void) -> SessionTaskType /// Collects tasks from backend networking stack. `handler` must be called after collecting. func getTasksWithHandler(_ handler: @escaping ([SessionTaskType]) -> Void) diff --git a/Sources/SessionAdapterType/URLSessionAdapter.swift b/Sources/SessionAdapterType/URLSessionAdapter.swift index dcac7072..b56712b5 100644 --- a/Sources/SessionAdapterType/URLSessionAdapter.swift +++ b/Sources/SessionAdapterType/URLSessionAdapter.swift @@ -25,7 +25,7 @@ open class URLSessionAdapter: NSObject, SessionAdapterType, URLSessionDelegate, } /// Creates `URLSessionDataTask` instance using `dataTaskWithRequest(_:completionHandler:)`. - open func createTaskWithURLRequest(_ URLRequest: URLRequest, handler: @escaping (NSData?, URLResponse?, Error?) -> Void) -> SessionTaskType { + open func createTaskWithURLRequest(_ URLRequest: URLRequest, handler: @escaping (Data?, URLResponse?, Error?) -> Void) -> SessionTaskType { let task = urlSession.dataTask(with: URLRequest) setBuffer(NSMutableData(), forTask: task) @@ -55,17 +55,17 @@ open class URLSessionAdapter: NSObject, SessionAdapterType, URLSessionDelegate, return objc_getAssociatedObject(task, &dataTaskResponseBufferKey) as? NSMutableData } - private func setHandler(_ handler: (NSData?, URLResponse?, Error?) -> Void, forTask task: URLSessionTask) { + private func setHandler(_ handler: (Data?, URLResponse?, Error?) -> Void, forTask task: URLSessionTask) { objc_setAssociatedObject(task, &taskAssociatedObjectCompletionHandlerKey, Box(handler), .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } - private func handlerForTask(_ task: URLSessionTask) -> ((NSData?, URLResponse?, Error?) -> Void)? { - return (objc_getAssociatedObject(task, &taskAssociatedObjectCompletionHandlerKey) as? Box<(NSData?, URLResponse?, Error?) -> Void>)?.value + private func handlerForTask(_ task: URLSessionTask) -> ((Data?, URLResponse?, Error?) -> Void)? { + return (objc_getAssociatedObject(task, &taskAssociatedObjectCompletionHandlerKey) as? Box<(Data?, URLResponse?, Error?) -> Void>)?.value } // MARK: URLSessionTaskDelegate open func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { - handlerForTask(task)?(bufferForTask(task), task.response, error) + handlerForTask(task)?(bufferForTask(task) as Data?, task.response, error) } // MARK: URLSessionDataDelegate diff --git a/Tests/APIKit/TestComponents/TestSessionAdapter.swift b/Tests/APIKit/TestComponents/TestSessionAdapter.swift index fe03c722..3e0de50c 100644 --- a/Tests/APIKit/TestComponents/TestSessionAdapter.swift +++ b/Tests/APIKit/TestComponents/TestSessionAdapter.swift @@ -42,14 +42,14 @@ class TestSessionAdapter: SessionAdapterType { if task.cancelled { task.handler(nil, nil, Error.cancelled) } else { - task.handler(data as NSData?, urlResponse, error) + task.handler(data, urlResponse, error) } } tasks = [] } - func createTaskWithURLRequest(_ URLRequest: URLRequest, handler: @escaping (NSData?, URLResponse?, Swift.Error?) -> Void) -> SessionTaskType { + func createTaskWithURLRequest(_ URLRequest: URLRequest, handler: @escaping (Data?, URLResponse?, Swift.Error?) -> Void) -> SessionTaskType { let task = TestSessionTask(handler: handler) tasks.append(task) diff --git a/Tests/APIKit/TestComponents/TestSessionTask.swift b/Tests/APIKit/TestComponents/TestSessionTask.swift index 6e62f1c8..50e96ed8 100644 --- a/Tests/APIKit/TestComponents/TestSessionTask.swift +++ b/Tests/APIKit/TestComponents/TestSessionTask.swift @@ -3,10 +3,10 @@ import APIKit class TestSessionTask: SessionTaskType { - var handler: (NSData?, URLResponse?, Error?) -> Void + var handler: (Data?, URLResponse?, Error?) -> Void var cancelled = false - init(handler: @escaping (NSData?, URLResponse?, Error?) -> Void) { + init(handler: @escaping (Data?, URLResponse?, Error?) -> Void) { self.handler = handler } From 0722e2d7b7d07a3bef76d26367fff0369f1feeb6 Mon Sep 17 00:00:00 2001 From: Syo Ikeda Date: Fri, 19 Aug 2016 01:39:41 +0900 Subject: [PATCH 18/38] Audit CallbackQueue cases --- Sources/CallbackQueue.swift | 18 +++++++++--------- Sources/Session.swift | 2 +- Tests/APIKit/SessionCallbackQueueTests.swift | 14 +++++++------- 3 files changed, 17 insertions(+), 17 deletions(-) diff --git a/Sources/CallbackQueue.swift b/Sources/CallbackQueue.swift index 540b835c..b689170c 100644 --- a/Sources/CallbackQueue.swift +++ b/Sources/CallbackQueue.swift @@ -3,33 +3,33 @@ import Foundation /// `CallbackQueue` represents queue where `handler` of `Session.sendRequest(_:handler:)` runs. public enum CallbackQueue { /// Dispatches callback closure on main queue asynchronously. - case Main + case main /// Dispatches callback closure on the queue where backend adapter callback runs. - case SessionQueue + case sessionQueue /// Dispatches callback closure on associated operation queue. - case OperationQueue(OperationQueue) + case operationQueue(OperationQueue) /// Dispatches callback closure on associated dispatch queue. - case DispatchQueue(Foundation.DispatchQueue) + case dispatchQueue(DispatchQueue) internal func execute(closure: @escaping () -> Void) { switch self { - case .Main: - Foundation.DispatchQueue.main.async { + case .main: + DispatchQueue.main.async { closure() } - case .SessionQueue: + case .sessionQueue: closure() - case .OperationQueue(let operationQueue): + case .operationQueue(let operationQueue): operationQueue.addOperation { closure() } - case .DispatchQueue(let dispatchQueue): + case .dispatchQueue(let dispatchQueue): dispatchQueue.async { closure() } diff --git a/Sources/Session.swift b/Sources/Session.swift index c44fc3f2..fb9567fb 100644 --- a/Sources/Session.swift +++ b/Sources/Session.swift @@ -14,7 +14,7 @@ open class Session { /// Returns `Session` instance that is initialized with `adapter`. /// - parameter adapter: The adapter that connects lower level backend with Session interface. /// - parameter callbackQueue: The default callback queue for `sendRequest(_:handler:)`. - public init(adapter: SessionAdapterType, callbackQueue: CallbackQueue = .Main) { + public init(adapter: SessionAdapterType, callbackQueue: CallbackQueue = .main) { self.adapter = adapter self.callbackQueue = callbackQueue } diff --git a/Tests/APIKit/SessionCallbackQueueTests.swift b/Tests/APIKit/SessionCallbackQueueTests.swift index 5f219fca..8b309519 100644 --- a/Tests/APIKit/SessionCallbackQueueTests.swift +++ b/Tests/APIKit/SessionCallbackQueueTests.swift @@ -13,14 +13,14 @@ class SessionCallbackQueueTests: XCTestCase { adapter = TestSessionAdapter() adapter.data = try! JSONSerialization.data(withJSONObject: ["key": "value"], options: []) - session = Session(adapter: adapter, callbackQueue: .Main) + session = Session(adapter: adapter, callbackQueue: .main) } func testMain() { let expectation = self.expectation(description: "wait for response") let request = TestRequest() - session.sendRequest(request, callbackQueue: .Main) { result in + session.sendRequest(request, callbackQueue: .main) { result in XCTAssert(Thread.isMainThread) expectation.fulfill() } @@ -32,7 +32,7 @@ class SessionCallbackQueueTests: XCTestCase { let expectation = self.expectation(description: "wait for response") let request = TestRequest() - session.sendRequest(request, callbackQueue: .SessionQueue) { result in + session.sendRequest(request, callbackQueue: .sessionQueue) { result in // This depends on implementation of TestSessionAdapter XCTAssert(Thread.isMainThread) expectation.fulfill() @@ -46,7 +46,7 @@ class SessionCallbackQueueTests: XCTestCase { let expectation = self.expectation(description: "wait for response") let request = TestRequest() - session.sendRequest(request, callbackQueue: .OperationQueue(operationQueue)) { result in + session.sendRequest(request, callbackQueue: .operationQueue(operationQueue)) { result in XCTAssertEqual(OperationQueue.current, operationQueue) expectation.fulfill() } @@ -59,7 +59,7 @@ class SessionCallbackQueueTests: XCTestCase { let expectation = self.expectation(description: "wait for response") let request = TestRequest() - session.sendRequest(request, callbackQueue: .DispatchQueue(dispatchQueue)) { result in + session.sendRequest(request, callbackQueue: .dispatchQueue(dispatchQueue)) { result in // There is no way to test current dispatch queue. XCTAssert(!Thread.isMainThread) expectation.fulfill() @@ -71,7 +71,7 @@ class SessionCallbackQueueTests: XCTestCase { // MARK: Test Session.callbackQueue func testImplicitSessionCallbackQueue() { let operationQueue = OperationQueue() - let session = Session(adapter: adapter, callbackQueue: .OperationQueue(operationQueue)) + let session = Session(adapter: adapter, callbackQueue: .operationQueue(operationQueue)) let expectation = self.expectation(description: "wait for response") let request = TestRequest() @@ -86,7 +86,7 @@ class SessionCallbackQueueTests: XCTestCase { func testExplicitSessionCallbackQueue() { let operationQueue = OperationQueue() - let session = Session(adapter: adapter, callbackQueue: .OperationQueue(operationQueue)) + let session = Session(adapter: adapter, callbackQueue: .operationQueue(operationQueue)) let expectation = self.expectation(description: "wait for response") let request = TestRequest() From 543756240f7d2b9b9ffab6e02a3de23f91debd47 Mon Sep 17 00:00:00 2001 From: Syo Ikeda Date: Fri, 19 Aug 2016 01:48:39 +0900 Subject: [PATCH 19/38] Fix Playground --- Demo.playground/Contents.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Demo.playground/Contents.swift b/Demo.playground/Contents.swift index 06ac452e..094afdf8 100644 --- a/Demo.playground/Contents.swift +++ b/Demo.playground/Contents.swift @@ -47,7 +47,7 @@ struct GetRateLimitRequest: GitHubRequestType { return "/rate_limit" } - func responseFromObject(_ object: AnyObject, urlResponse: HTTPURLResponse) throws -> Response { + func responseFromObject(_ object: Any, urlResponse: HTTPURLResponse) throws -> Response { guard let dictionary = object as? [String: AnyObject], let rateLimit = RateLimit(dictionary: dictionary) else { throw ResponseError.UnexpectedObject(object) From f36f0878ea4568b770a8ff01ea72fc7d9769a7ec Mon Sep 17 00:00:00 2001 From: Syo Ikeda Date: Fri, 19 Aug 2016 01:51:51 +0900 Subject: [PATCH 20/38] Rename responseFromObject --- Demo.playground/Contents.swift | 2 +- Sources/RequestType.swift | 4 ++-- Tests/APIKit/SessionTests.swift | 2 +- Tests/APIKit/TestComponents/TestRequest.swift | 2 +- 4 files changed, 5 insertions(+), 5 deletions(-) diff --git a/Demo.playground/Contents.swift b/Demo.playground/Contents.swift index 094afdf8..90a926fc 100644 --- a/Demo.playground/Contents.swift +++ b/Demo.playground/Contents.swift @@ -47,7 +47,7 @@ struct GetRateLimitRequest: GitHubRequestType { return "/rate_limit" } - func responseFromObject(_ object: Any, urlResponse: HTTPURLResponse) throws -> Response { + func response(from object: Any, urlResponse: HTTPURLResponse) throws -> Response { guard let dictionary = object as? [String: AnyObject], let rateLimit = RateLimit(dictionary: dictionary) else { throw ResponseError.UnexpectedObject(object) diff --git a/Sources/RequestType.swift b/Sources/RequestType.swift index b6e57f6b..8bcf0f42 100644 --- a/Sources/RequestType.swift +++ b/Sources/RequestType.swift @@ -58,7 +58,7 @@ public protocol RequestType { /// Build `Response` instance from raw response object. This method is called after /// `interceptObject(:URLResponse:)` if it does not throw any error. /// - Throws: `ErrorType` - func responseFromObject(_ object: Any, urlResponse: HTTPURLResponse) throws -> Response + func response(from object: Any, urlResponse: HTTPURLResponse) throws -> Response } public extension RequestType { @@ -143,6 +143,6 @@ public extension RequestType { public func parseData(_ data: Data, urlResponse: HTTPURLResponse) throws -> Response { let parsedObject = try dataParser.parseData(data) let passedObject = try interceptObject(parsedObject, urlResponse: urlResponse) - return try responseFromObject(passedObject, urlResponse: urlResponse) + return try response(from: passedObject, urlResponse: urlResponse) } } diff --git a/Tests/APIKit/SessionTests.swift b/Tests/APIKit/SessionTests.swift index 804cdfce..792081e6 100644 --- a/Tests/APIKit/SessionTests.swift +++ b/Tests/APIKit/SessionTests.swift @@ -191,7 +191,7 @@ class SessionTests: XCTestCase { return "/" } - func responseFromObject(_ object: Any, urlResponse: HTTPURLResponse) throws -> Response { + func response(from object: Any, urlResponse: HTTPURLResponse) throws -> Response { return () } } diff --git a/Tests/APIKit/TestComponents/TestRequest.swift b/Tests/APIKit/TestComponents/TestRequest.swift index a3f98192..cf311b78 100644 --- a/Tests/APIKit/TestComponents/TestRequest.swift +++ b/Tests/APIKit/TestComponents/TestRequest.swift @@ -30,7 +30,7 @@ struct TestRequest: RequestType { return try interceptURLRequest(urlRequest) } - func responseFromObject(_ object: Any, urlResponse: HTTPURLResponse) throws -> Response { + func response(from object: Any, urlResponse: HTTPURLResponse) throws -> Response { return object } } From d2b9fbdfd2e6906736831f5e4f88e239e8b38823 Mon Sep 17 00:00:00 2001 From: Syo Ikeda Date: Tue, 23 Aug 2016 09:18:55 +0900 Subject: [PATCH 21/38] Switch back to AliSoftware/OHHTTPStubs --- .gitmodules | 2 +- Cartfile.private | 2 +- Cartfile.resolved | 2 +- Carthage/Checkouts/OHHTTPStubs | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/.gitmodules b/.gitmodules index fc535505..30480090 100644 --- a/.gitmodules +++ b/.gitmodules @@ -3,4 +3,4 @@ url = https://github.com/antitypical/Result.git [submodule "Carthage/Checkouts/OHHTTPStubs"] path = Carthage/Checkouts/OHHTTPStubs - url = https://github.com/ikesyo/OHHTTPStubs.git + url = https://github.com/AliSoftware/OHHTTPStubs.git diff --git a/Cartfile.private b/Cartfile.private index 95495240..5649a9f9 100644 --- a/Cartfile.private +++ b/Cartfile.private @@ -1 +1 @@ -github "ikesyo/OHHTTPStubs" "swift3" +github "AliSoftware/OHHTTPStubs" "5.2.0-swift3" diff --git a/Cartfile.resolved b/Cartfile.resolved index e0ee8dc0..8fb10e7d 100644 --- a/Cartfile.resolved +++ b/Cartfile.resolved @@ -1,2 +1,2 @@ -github "ikesyo/OHHTTPStubs" "a2e8edf5fc75adc80bd17743a07b262d3f3063b3" +github "AliSoftware/OHHTTPStubs" "5.2.0-swift3" github "antitypical/Result" "3.0.0-alpha.3" diff --git a/Carthage/Checkouts/OHHTTPStubs b/Carthage/Checkouts/OHHTTPStubs index a2e8edf5..5198de9d 160000 --- a/Carthage/Checkouts/OHHTTPStubs +++ b/Carthage/Checkouts/OHHTTPStubs @@ -1 +1 @@ -Subproject commit a2e8edf5fc75adc80bd17743a07b262d3f3063b3 +Subproject commit 5198de9d0ab671b03a3c67540a6e983737c8eddc From 0cbac6902e47e9e2cbee80029ec6308955ba5741 Mon Sep 17 00:00:00 2001 From: Syo Ikeda Date: Tue, 23 Aug 2016 23:32:08 +0900 Subject: [PATCH 22/38] Lowercase enum cases --- Demo.playground/Contents.swift | 4 +-- .../BodyParametersType.swift | 4 +-- .../BodyParametersType/Data+InputStream.swift | 6 ++-- .../FormURLEncodedBodyParameters.swift | 4 +-- .../JSONBodyParameters.swift | 4 +-- .../MultipartFormDataBodyParameters.swift | 28 +++++++++---------- .../FormURLEncodedDataParser.swift | 4 +-- Sources/DataParserType/StringDataParser.swift | 4 +-- Sources/Error/RequestError.swift | 4 +-- Sources/Error/ResponseError.swift | 6 ++-- Sources/Error/SessionTaskError.swift | 6 ++-- Sources/HTTPMethod.swift | 20 ++++++------- Sources/RequestType.swift | 14 +++++----- .../URLEncodedSerialization.swift | 16 +++++------ Sources/Session.swift | 8 +++--- .../FormURLEncodedBodyParametersTests.swift | 2 +- .../JSONBodyParametersTests.swift | 2 +- .../MultipartFormDataParametersTests.swift | 14 +++++----- .../URLEncodedSerializationTests.swift | 6 ++-- .../FormURLEncodedDataParserTests.swift | 2 +- .../StringDataParserTests.swift | 2 +- Tests/APIKit/RequestTypeTests.swift | 4 +-- .../URLSessionAdapterTests.swift | 4 +-- Tests/APIKit/SessionTests.swift | 16 +++++------ Tests/APIKit/TestComponents/TestRequest.swift | 2 +- 25 files changed, 93 insertions(+), 93 deletions(-) diff --git a/Demo.playground/Contents.swift b/Demo.playground/Contents.swift index 90a926fc..f4a73188 100644 --- a/Demo.playground/Contents.swift +++ b/Demo.playground/Contents.swift @@ -40,7 +40,7 @@ struct GetRateLimitRequest: GitHubRequestType { typealias Response = RateLimit var method: HTTPMethod { - return .GET + return .get } var path: String { @@ -50,7 +50,7 @@ struct GetRateLimitRequest: GitHubRequestType { func response(from object: Any, urlResponse: HTTPURLResponse) throws -> Response { guard let dictionary = object as? [String: AnyObject], let rateLimit = RateLimit(dictionary: dictionary) else { - throw ResponseError.UnexpectedObject(object) + throw ResponseError.unexpectedObject(object) } return rateLimit diff --git a/Sources/BodyParametersType/BodyParametersType.swift b/Sources/BodyParametersType/BodyParametersType.swift index f6056b20..14c0d32e 100644 --- a/Sources/BodyParametersType/BodyParametersType.swift +++ b/Sources/BodyParametersType/BodyParametersType.swift @@ -3,10 +3,10 @@ import Foundation /// `RequestBodyEntity` represents entity of HTTP body. public enum RequestBodyEntity { /// Expresses entity as `Data`. The associated value will be set to `URLRequest.HTTPBody`. - case Data(Data) + case data(Data) /// Expresses entity as `InputStream`. The associated value will be set to `URLRequest.HTTPBodyStream`. - case InputStream(InputStream) + case inputStream(InputStream) } /// `BodyParametersType` provides interface to parse HTTP response body and to state `Content-Type` to accept. diff --git a/Sources/BodyParametersType/Data+InputStream.swift b/Sources/BodyParametersType/Data+InputStream.swift index 8e812154..7ef698d8 100644 --- a/Sources/BodyParametersType/Data+InputStream.swift +++ b/Sources/BodyParametersType/Data+InputStream.swift @@ -1,8 +1,8 @@ import Foundation enum InputStreamError: Error { - case InvalidDataCapacity(Int) - case UnreadableStream(InputStream) + case invalidDataCapacity(Int) + case unreadableStream(InputStream) } extension Data { @@ -22,7 +22,7 @@ extension Data { data.append(buffer, count: readSize) case let x where x < 0: - throw InputStreamError.UnreadableStream(inputStream) + throw InputStreamError.unreadableStream(inputStream) default: break diff --git a/Sources/BodyParametersType/FormURLEncodedBodyParameters.swift b/Sources/BodyParametersType/FormURLEncodedBodyParameters.swift index 52ba3332..d38c1c21 100644 --- a/Sources/BodyParametersType/FormURLEncodedBodyParameters.swift +++ b/Sources/BodyParametersType/FormURLEncodedBodyParameters.swift @@ -21,9 +21,9 @@ public struct FormURLEncodedBodyParameters: BodyParametersType { return "application/x-www-form-urlencoded" } - /// Builds `RequestBodyEntity.Data` that represents `form`. + /// Builds `RequestBodyEntity.data` that represents `form`. /// - Throws: `URLEncodedSerialization.Error` if `URLEncodedSerialization` fails to serialize form object. public func buildEntity() throws -> RequestBodyEntity { - return .Data(try URLEncodedSerialization.dataFromObject(form, encoding: encoding)) + return .data(try URLEncodedSerialization.dataFromObject(form, encoding: encoding)) } } diff --git a/Sources/BodyParametersType/JSONBodyParameters.swift b/Sources/BodyParametersType/JSONBodyParameters.swift index 30c84ae0..7a8eabf6 100644 --- a/Sources/BodyParametersType/JSONBodyParameters.swift +++ b/Sources/BodyParametersType/JSONBodyParameters.swift @@ -21,7 +21,7 @@ public struct JSONBodyParameters: BodyParametersType { return "application/json" } - /// Builds `RequestBodyEntity.Data` that represents `JSONObject`. + /// Builds `RequestBodyEntity.data` that represents `JSONObject`. /// - Throws: `NSError` if `JSONSerialization` fails to serialize `JSONObject`. public func buildEntity() throws -> RequestBodyEntity { // If isValidJSONObject(_:) is false, dataWithJSONObject(_:options:) throws NSException. @@ -29,6 +29,6 @@ public struct JSONBodyParameters: BodyParametersType { throw NSError(domain: NSCocoaErrorDomain, code: 3840, userInfo: nil) } - return .Data(try JSONSerialization.data(withJSONObject: JSONObject, options: writingOptions)) + return .data(try JSONSerialization.data(withJSONObject: JSONObject, options: writingOptions)) } } diff --git a/Sources/BodyParametersType/MultipartFormDataBodyParameters.swift b/Sources/BodyParametersType/MultipartFormDataBodyParameters.swift index 6ac3bfca..999da390 100644 --- a/Sources/BodyParametersType/MultipartFormDataBodyParameters.swift +++ b/Sources/BodyParametersType/MultipartFormDataBodyParameters.swift @@ -11,17 +11,17 @@ public struct MultipartFormDataBodyParameters: BodyParametersType { /// `EntityType` represents wheather the entity is expressed as `Data` or `InputStream`. public enum EntityType { /// Expresses the entity as `Data`, which has faster upload speed and lager memory usage. - case Data + case data /// Expresses the entity as `InputStream`, which has smaller memory usage and slower upload speed. - case InputStream + case inputStream } public let parts: [Part] public let boundary: String public let entityType: EntityType - public init(parts: [Part], boundary: String = String(format: "%08x%08x", arc4random(), arc4random()), entityType: EntityType = .Data) { + public init(parts: [Part], boundary: String = String(format: "%08x%08x", arc4random(), arc4random()), entityType: EntityType = .data) { self.parts = parts self.boundary = boundary self.entityType = entityType @@ -34,16 +34,16 @@ public struct MultipartFormDataBodyParameters: BodyParametersType { return "multipart/form-data; boundary=\(boundary)" } - /// Builds `RequestBodyEntity.Data` that represents `form`. + /// Builds `RequestBodyEntity.data` that represents `form`. public func buildEntity() throws -> RequestBodyEntity { let inputStream = MultipartInputStream(parts: parts, boundary: boundary) switch entityType { - case .InputStream: - return .InputStream(inputStream) + case .inputStream: + return .inputStream(inputStream) - case .Data: - return .Data(try Data(inputStream: inputStream)) + case .data: + return .data(try Data(inputStream: inputStream)) } } } @@ -52,9 +52,9 @@ public extension MultipartFormDataBodyParameters { /// Part represents single part of multipart/form-data. public struct Part { public enum Error: Swift.Error { - case IllegalValue(Any) - case IllegalFileURL(URL) - case CannotGetFileSize(URL) + case illegalValue(Any) + case illegalFileURL(URL) + case cannotGetFileSize(URL) } public let inputStream: InputStream @@ -68,7 +68,7 @@ public extension MultipartFormDataBodyParameters { /// If `mimeType` or `fileName` are `nil`, the fields will be omitted. public init(value: Any, name: String, mimeType: String? = nil, fileName: String? = nil, encoding: String.Encoding = .utf8) throws { guard let data = String(describing: value).data(using: encoding) else { - throw Error.IllegalValue(value) + throw Error.illegalValue(value) } self.inputStream = InputStream(data: data) @@ -92,7 +92,7 @@ public extension MultipartFormDataBodyParameters { /// If `mimeType` or `fileName` are `nil`, values for the fields will be detected from URL. public init(fileUrl: URL, name: String, mimeType: String? = nil, fileName: String? = nil) throws { guard let inputStream = InputStream(url: fileUrl) else { - throw Error.IllegalFileURL(fileUrl) + throw Error.illegalFileURL(fileUrl) } let fileSize = (try? FileManager.default.attributesOfItem(atPath: fileUrl.path)) @@ -100,7 +100,7 @@ public extension MultipartFormDataBodyParameters { .map { $0.intValue } guard let bodyLength = fileSize else { - throw Error.CannotGetFileSize(fileUrl) + throw Error.cannotGetFileSize(fileUrl) } let detectedMimeType = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, fileUrl.pathExtension as CFString, nil) diff --git a/Sources/DataParserType/FormURLEncodedDataParser.swift b/Sources/DataParserType/FormURLEncodedDataParser.swift index 273c510b..a205a014 100644 --- a/Sources/DataParserType/FormURLEncodedDataParser.swift +++ b/Sources/DataParserType/FormURLEncodedDataParser.swift @@ -3,7 +3,7 @@ import Foundation /// `FormURLEncodedDataParser` parses form URL encoded response data. public class FormURLEncodedDataParser: DataParserType { public enum Error: Swift.Error { - case CannotGetStringFromData(Data) + case cannotGetStringFromData(Data) } /// The string encoding of the data. @@ -25,7 +25,7 @@ public class FormURLEncodedDataParser: DataParserType { /// - Throws: `FormURLEncodedDataParser.Error` when the parser fails to initialize `String` from `Data`. public func parseData(_ data: Data) throws -> Any { guard let string = String(data: data, encoding: encoding) else { - throw Error.CannotGetStringFromData(data) + throw Error.cannotGetStringFromData(data) } var components = URLComponents() diff --git a/Sources/DataParserType/StringDataParser.swift b/Sources/DataParserType/StringDataParser.swift index d8d363e1..7a51fe23 100644 --- a/Sources/DataParserType/StringDataParser.swift +++ b/Sources/DataParserType/StringDataParser.swift @@ -3,7 +3,7 @@ import Foundation /// `StringDataParser` parses data and convert it to string. public class StringDataParser: DataParserType { public enum Error: Swift.Error { - case InvalidData(Data) + case invalidData(Data) } /// The string encoding of the data. @@ -25,7 +25,7 @@ public class StringDataParser: DataParserType { /// - Throws: `StringDataParser.Error` when the parser fails to initialize `String` from `Data`. public func parseData(_ data: Data) throws -> Any { guard let string = String(data: data, encoding: encoding) else { - throw Error.InvalidData(data) + throw Error.invalidData(data) } return string diff --git a/Sources/Error/RequestError.swift b/Sources/Error/RequestError.swift index 17870ba2..06380dde 100644 --- a/Sources/Error/RequestError.swift +++ b/Sources/Error/RequestError.swift @@ -3,8 +3,8 @@ import Foundation /// `RequestError` represents a common error that occurs while building `URLRequest` from `RequestType`. public enum RequestError: Error { /// Indicates `baseUrl` of a type that conforms `RequestType` is invalid. - case InvalidBaseURL(URL) + case invalidBaseURL(URL) /// Indicates `URLRequest` built by `RequestType.buildURLRequest` is unexpected. - case UnexpectedURLRequest(URLRequest) + case unexpectedURLRequest(URLRequest) } diff --git a/Sources/Error/ResponseError.swift b/Sources/Error/ResponseError.swift index d8dde149..e2e61859 100644 --- a/Sources/Error/ResponseError.swift +++ b/Sources/Error/ResponseError.swift @@ -4,12 +4,12 @@ import Foundation /// from raw result tuple `(Data?, URLResponse?, Error?)`. public enum ResponseError: Error { /// Indicates the session adapter returned `URLResponse` that fails to down-cast to `HTTPURLResponse`. - case NonHTTPURLResponse(URLResponse?) + case nonHTTPURLResponse(URLResponse?) /// Indicates `HTTPURLResponse.statusCode` is not acceptable. /// In most cases, *acceptable* means the value is in `200..<300`. - case UnacceptableStatusCode(Int) + case unacceptableStatusCode(Int) /// Indicates `Any` that represents the response is unexpected. - case UnexpectedObject(Any) + case unexpectedObject(Any) } diff --git a/Sources/Error/SessionTaskError.swift b/Sources/Error/SessionTaskError.swift index d10c4ba7..ed46880e 100644 --- a/Sources/Error/SessionTaskError.swift +++ b/Sources/Error/SessionTaskError.swift @@ -3,11 +3,11 @@ import Foundation /// `SessionTaskError` represents an error that occurs while task for a request. public enum SessionTaskError: Error { /// Error of `URLSession`. - case ConnectionError(Error) + case connectionError(Error) /// Error while creating `URLReqeust` from `Request`. - case RequestError(Error) + case requestError(Error) /// Error while creating `RequestType.Response` from `(Data, URLResponse)`. - case ResponseError(Error) + case responseError(Error) } diff --git a/Sources/HTTPMethod.swift b/Sources/HTTPMethod.swift index d6ceaa1d..6a29f58e 100644 --- a/Sources/HTTPMethod.swift +++ b/Sources/HTTPMethod.swift @@ -2,20 +2,20 @@ import Foundation /// `HTTPMethod` represents HTTP methods. public enum HTTPMethod: String { - case GET - case POST - case PUT - case HEAD - case DELETE - case PATCH - case TRACE - case OPTIONS - case CONNECT + case get = "GET" + case post = "POST" + case put = "PUT" + case head = "HEAD" + case delete = "DELETE" + case patch = "PATCH" + case trace = "TRACE" + case options = "OPTIONS" + case connect = "CONNECT" /// Indicates if the query parameters are suitable for parameters. public var prefersQueryParameters: Bool { switch self { - case .GET, .HEAD, .DELETE: + case .get, .head, .delete: return true default: diff --git a/Sources/RequestType.swift b/Sources/RequestType.swift index 8bcf0f42..48f6a8aa 100644 --- a/Sources/RequestType.swift +++ b/Sources/RequestType.swift @@ -44,13 +44,13 @@ public protocol RequestType { var dataParser: DataParserType { get } /// Intercepts `URLRequest` which is created by `RequestType.buildURLRequest()`. If an error is - /// thrown in this method, the result of `Session.sendRequest()` turns `.failure(.RequestError(error))`. + /// thrown in this method, the result of `Session.sendRequest()` turns `.failure(.requestError(error))`. /// - Throws: `ErrorType` func interceptURLRequest(_ urlRequest: URLRequest) throws -> URLRequest /// Intercepts response `Any` and `HTTPURLResponse`. If an error is thrown in this method, - /// the result of `Session.sendRequest()` turns `.failure(.ResponseError(error))`. - /// The default implementation of this method is provided to throw `RequestError.UnacceptableStatusCode` + /// the result of `Session.sendRequest()` turns `.failure(.responseError(error))`. + /// The default implementation of this method is provided to throw `RequestError.unacceptableStatusCode` /// if the HTTP status code is not in `200..<300`. /// - Throws: `ErrorType` func interceptObject(_ object: Any, urlResponse: HTTPURLResponse) throws -> Any @@ -96,7 +96,7 @@ public extension RequestType { public func interceptObject(_ object: Any, urlResponse: HTTPURLResponse) throws -> Any { guard (200..<300).contains(urlResponse.statusCode) else { - throw ResponseError.UnacceptableStatusCode(urlResponse.statusCode) + throw ResponseError.unacceptableStatusCode(urlResponse.statusCode) } return object } @@ -106,7 +106,7 @@ public extension RequestType { public func buildURLRequest() throws -> URLRequest { let url = path.isEmpty ? baseUrl : baseUrl.appendingPathComponent(path) guard var components = URLComponents(url: url, resolvingAgainstBaseURL: true) else { - throw RequestError.InvalidBaseURL(baseUrl) + throw RequestError.invalidBaseURL(baseUrl) } var urlRequest = URLRequest(url: url) @@ -119,10 +119,10 @@ public extension RequestType { urlRequest.setValue(bodyParameters.contentType, forHTTPHeaderField: "Content-Type") switch try bodyParameters.buildEntity() { - case .Data(let data): + case .data(let data): urlRequest.httpBody = data - case .InputStream(let inputStream): + case .inputStream(let inputStream): urlRequest.httpBodyStream = inputStream } } diff --git a/Sources/Serializations/URLEncodedSerialization.swift b/Sources/Serializations/URLEncodedSerialization.swift index 0f6f70cb..7d81a97d 100644 --- a/Sources/Serializations/URLEncodedSerialization.swift +++ b/Sources/Serializations/URLEncodedSerialization.swift @@ -45,17 +45,17 @@ private func unescape(_ string: String) -> String { /// and returns dictionary that represents the data or the string. public final class URLEncodedSerialization { public enum Error: Swift.Error { - case CannotGetStringFromData(Data, String.Encoding) - case CannotGetDataFromString(String, String.Encoding) - case CannotCastObjectToDictionary(Any) - case InvalidFormatString(String) + case cannotGetStringFromData(Data, String.Encoding) + case cannotGetDataFromString(String, String.Encoding) + case cannotCastObjectToDictionary(Any) + case invalidFormatString(String) } /// Returns `[String: String]` that represents urlencoded `Data`. /// - Throws: URLEncodedSerialization.Error public static func objectFromData(_ data: Data, encoding: String.Encoding) throws -> [String: String] { guard let string = String(data: data, encoding: encoding) else { - throw Error.CannotGetStringFromData(data, encoding) + throw Error.cannotGetStringFromData(data, encoding) } var dictionary = [String: String]() @@ -63,7 +63,7 @@ public final class URLEncodedSerialization { let contents = pair.components(separatedBy: "=") guard contents.count == 2 else { - throw Error.InvalidFormatString(string) + throw Error.invalidFormatString(string) } dictionary[contents[0]] = unescape(contents[1]) @@ -76,12 +76,12 @@ public final class URLEncodedSerialization { /// - Throws: URLEncodedSerialization.Error public static func dataFromObject(_ object: Any, encoding: String.Encoding) throws -> Data { guard let dictionary = object as? [String: Any] else { - throw Error.CannotCastObjectToDictionary(object) + throw Error.cannotCastObjectToDictionary(object) } let string = stringFromDictionary(dictionary) guard let data = string.data(using: encoding, allowLossyConversion: false) else { - throw Error.CannotGetDataFromString(string, encoding) + throw Error.cannotGetDataFromString(string, encoding) } return data diff --git a/Sources/Session.swift b/Sources/Session.swift index fb9567fb..390aed31 100644 --- a/Sources/Session.swift +++ b/Sources/Session.swift @@ -63,7 +63,7 @@ open class Session { urlRequest = try request.buildURLRequest() } catch { callbackQueue.execute { - handler(.failure(.RequestError(error))) + handler(.failure(.requestError(error))) } return nil } @@ -73,17 +73,17 @@ open class Session { switch (data, urlResponse, error) { case (_, _, let error?): - result = .failure(.ConnectionError(error)) + result = .failure(.connectionError(error)) case (let data?, let urlResponse as HTTPURLResponse, _): do { result = .success(try request.parseData(data as Data, urlResponse: urlResponse)) } catch { - result = .failure(.ResponseError(error)) + result = .failure(.responseError(error)) } default: - result = .failure(.ResponseError(ResponseError.NonHTTPURLResponse(urlResponse))) + result = .failure(.responseError(ResponseError.nonHTTPURLResponse(urlResponse))) } callbackQueue.execute { diff --git a/Tests/APIKit/BodyParametersType/FormURLEncodedBodyParametersTests.swift b/Tests/APIKit/BodyParametersType/FormURLEncodedBodyParametersTests.swift index 1c360db4..803ce218 100644 --- a/Tests/APIKit/BodyParametersType/FormURLEncodedBodyParametersTests.swift +++ b/Tests/APIKit/BodyParametersType/FormURLEncodedBodyParametersTests.swift @@ -9,7 +9,7 @@ class FormURLEncodedBodyParametersTests: XCTestCase { XCTAssertEqual(parameters.contentType, "application/x-www-form-urlencoded") do { - guard case .Data(let data) = try parameters.buildEntity() else { + guard case .data(let data) = try parameters.buildEntity() else { XCTFail() return } diff --git a/Tests/APIKit/BodyParametersType/JSONBodyParametersTests.swift b/Tests/APIKit/BodyParametersType/JSONBodyParametersTests.swift index 100ae810..006c8e04 100644 --- a/Tests/APIKit/BodyParametersType/JSONBodyParametersTests.swift +++ b/Tests/APIKit/BodyParametersType/JSONBodyParametersTests.swift @@ -9,7 +9,7 @@ class JSONBodyParametersTests: XCTestCase { XCTAssertEqual(parameters.contentType, "application/json") do { - guard case .Data(let data) = try parameters.buildEntity() else { + guard case .data(let data) = try parameters.buildEntity() else { XCTFail() return } diff --git a/Tests/APIKit/BodyParametersType/MultipartFormDataParametersTests.swift b/Tests/APIKit/BodyParametersType/MultipartFormDataParametersTests.swift index 77998290..2178854b 100644 --- a/Tests/APIKit/BodyParametersType/MultipartFormDataParametersTests.swift +++ b/Tests/APIKit/BodyParametersType/MultipartFormDataParametersTests.swift @@ -14,7 +14,7 @@ class MultipartFormDataParametersTests: XCTestCase { ]) do { - guard case .Data(let data) = try parameters.buildEntity() else { + guard case .data(let data) = try parameters.buildEntity() else { XCTFail() return } @@ -43,10 +43,10 @@ class MultipartFormDataParametersTests: XCTestCase { let parameters = MultipartFormDataBodyParameters(parts: [ MultipartFormDataBodyParameters.Part(data: value1, name: "foo"), MultipartFormDataBodyParameters.Part(data: value2, name: "bar"), - ], entityType: .InputStream) + ], entityType: .inputStream) do { - guard case .InputStream(let inputStream) = try parameters.buildEntity() else { + guard case .inputStream(let inputStream) = try parameters.buildEntity() else { XCTFail() return } @@ -76,7 +76,7 @@ class MultipartFormDataParametersTests: XCTestCase { let parameters = MultipartFormDataBodyParameters(parts: [part]) do { - guard case .Data(let data) = try parameters.buildEntity() else { + guard case .data(let data) = try parameters.buildEntity() else { XCTFail() return } @@ -106,7 +106,7 @@ class MultipartFormDataParametersTests: XCTestCase { let parameters = MultipartFormDataBodyParameters(parts: [part]) do { - guard case .Data(let data) = try parameters.buildEntity() else { + guard case .data(let data) = try parameters.buildEntity() else { XCTFail() return } @@ -123,7 +123,7 @@ class MultipartFormDataParametersTests: XCTestCase { let parameters = MultipartFormDataBodyParameters(parts: [part]) do { - guard case .Data(let data) = try parameters.buildEntity() else { + guard case .data(let data) = try parameters.buildEntity() else { XCTFail() return } @@ -140,7 +140,7 @@ class MultipartFormDataParametersTests: XCTestCase { let parameters = MultipartFormDataBodyParameters(parts: [part]) do { - guard case .Data(let data) = try parameters.buildEntity() else { + guard case .data(let data) = try parameters.buildEntity() else { XCTFail() return } diff --git a/Tests/APIKit/BodyParametersType/URLEncodedSerializationTests.swift b/Tests/APIKit/BodyParametersType/URLEncodedSerializationTests.swift index 7d81fef8..5cdb0983 100644 --- a/Tests/APIKit/BodyParametersType/URLEncodedSerializationTests.swift +++ b/Tests/APIKit/BodyParametersType/URLEncodedSerializationTests.swift @@ -20,7 +20,7 @@ class URLEncodedSerializationTests: XCTestCase { XCTFail() } catch { guard let error = error as? URLEncodedSerialization.Error, - case .InvalidFormatString(let invalidString) = error else { + case .invalidFormatString(let invalidString) = error else { XCTFail() return } @@ -38,7 +38,7 @@ class URLEncodedSerializationTests: XCTestCase { XCTFail() } catch { guard let error = error as? URLEncodedSerialization.Error, - case .CannotGetStringFromData(let invalidData, let encoding) = error else { + case .cannotGetStringFromData(let invalidData, let encoding) = error else { XCTFail() return } @@ -64,7 +64,7 @@ class URLEncodedSerializationTests: XCTestCase { XCTFail() } catch { guard let error = error as? URLEncodedSerialization.Error, - case .CannotCastObjectToDictionary(let object) = error else { + case .cannotCastObjectToDictionary(let object) = error else { XCTFail() return } diff --git a/Tests/APIKit/DataParserType/FormURLEncodedDataParserTests.swift b/Tests/APIKit/DataParserType/FormURLEncodedDataParserTests.swift index 75c5b6a3..4c46ea1d 100644 --- a/Tests/APIKit/DataParserType/FormURLEncodedDataParserTests.swift +++ b/Tests/APIKit/DataParserType/FormURLEncodedDataParserTests.swift @@ -34,7 +34,7 @@ class FormURLEncodedDataParserTests: XCTestCase { XCTFail() } catch { guard let error = error as? FormURLEncodedDataParser.Error, - case .CannotGetStringFromData(let invalidData) = error else { + case .cannotGetStringFromData(let invalidData) = error else { XCTFail() return } diff --git a/Tests/APIKit/DataParserType/StringDataParserTests.swift b/Tests/APIKit/DataParserType/StringDataParserTests.swift index a29d54d3..bc104476 100644 --- a/Tests/APIKit/DataParserType/StringDataParserTests.swift +++ b/Tests/APIKit/DataParserType/StringDataParserTests.swift @@ -31,7 +31,7 @@ class StringDataParserTests: XCTestCase { XCTFail() } catch { guard let error = error as? StringDataParser.Error, - case .InvalidData(let invalidData) = error else { + case .invalidData(let invalidData) = error else { XCTFail() return } diff --git a/Tests/APIKit/RequestTypeTests.swift b/Tests/APIKit/RequestTypeTests.swift index c5fae65b..c19d3ad0 100644 --- a/Tests/APIKit/RequestTypeTests.swift +++ b/Tests/APIKit/RequestTypeTests.swift @@ -35,7 +35,7 @@ class RequestTypeTests: XCTestCase { ["hello", "yellow"] ] - let request = TestRequest(method: .POST, parameters: parameters) + let request = TestRequest(method: .post, parameters: parameters) XCTAssert((request.parameters as? [Any])?.count == 3) let urlRequest = try? request.buildURLRequest() @@ -52,7 +52,7 @@ class RequestTypeTests: XCTestCase { } func testPOSTInvalidJSONRequest() { - let request = TestRequest(method: .POST, parameters: "foo") + let request = TestRequest(method: .post, parameters: "foo") let urlRequest = try? request.buildURLRequest() XCTAssertNil(urlRequest?.httpBody) } diff --git a/Tests/APIKit/SessionAdapterType/URLSessionAdapterTests.swift b/Tests/APIKit/SessionAdapterType/URLSessionAdapterTests.swift index e29b2439..43f1ab74 100644 --- a/Tests/APIKit/SessionAdapterType/URLSessionAdapterTests.swift +++ b/Tests/APIKit/SessionAdapterType/URLSessionAdapterTests.swift @@ -67,7 +67,7 @@ class URLSessionAdapterTests: XCTestCase { case .failure(let error): switch error { - case .ConnectionError(let error as NSError): + case .connectionError(let error as NSError): XCTAssertEqual(error.domain, NSURLErrorDomain) default: @@ -95,7 +95,7 @@ class URLSessionAdapterTests: XCTestCase { session.sendRequest(request) { result in guard case .failure(let error) = result, - case .ConnectionError(let connectionError as NSError) = error else { + case .connectionError(let connectionError as NSError) = error else { XCTFail() return } diff --git a/Tests/APIKit/SessionTests.swift b/Tests/APIKit/SessionTests.swift index 792081e6..8cf92d68 100644 --- a/Tests/APIKit/SessionTests.swift +++ b/Tests/APIKit/SessionTests.swift @@ -46,7 +46,7 @@ class SessionTests: XCTestCase { session.sendRequest(request) { result in if case .failure(let error) = result, - case .ResponseError(let responseError as NSError) = error { + case .responseError(let responseError as NSError) = error { XCTAssertEqual(responseError.domain, NSCocoaErrorDomain) XCTAssertEqual(responseError.code, 3840) } else { @@ -67,8 +67,8 @@ class SessionTests: XCTestCase { session.sendRequest(request) { result in if case .failure(let error) = result, - case .ResponseError(let responseError as ResponseError) = error, - case .UnacceptableStatusCode(let statusCode) = responseError { + case .responseError(let responseError as ResponseError) = error, + case .unacceptableStatusCode(let statusCode) = responseError { XCTAssertEqual(statusCode, 400) } else { XCTFail() @@ -88,8 +88,8 @@ class SessionTests: XCTestCase { session.sendRequest(request) { result in if case .failure(let error) = result, - case .ResponseError(let responseError as ResponseError) = error, - case .NonHTTPURLResponse(let urlResponse) = responseError { + case .responseError(let responseError as ResponseError) = error, + case .nonHTTPURLResponse(let urlResponse) = responseError { XCTAssert(urlResponse === self.adapter.urlResponse) } else { XCTFail() @@ -112,7 +112,7 @@ class SessionTests: XCTestCase { session.sendRequest(request) { result in if case .failure(let error) = result, - case .RequestError(let requestError) = error { + case .requestError(let requestError) = error { XCTAssert(requestError is Error) } else { XCTFail() @@ -132,7 +132,7 @@ class SessionTests: XCTestCase { session.sendRequest(request) { result in if case .failure(let error) = result, - case .ConnectionError(let connectionError as NSError) = error { + case .connectionError(let connectionError as NSError) = error { XCTAssertEqual(connectionError.code, 0) } else { XCTFail() @@ -184,7 +184,7 @@ class SessionTests: XCTestCase { } var method: HTTPMethod { - return .GET + return .get } var path: String { diff --git a/Tests/APIKit/TestComponents/TestRequest.swift b/Tests/APIKit/TestComponents/TestRequest.swift index cf311b78..549e4161 100644 --- a/Tests/APIKit/TestComponents/TestRequest.swift +++ b/Tests/APIKit/TestComponents/TestRequest.swift @@ -10,7 +10,7 @@ struct TestRequest: RequestType { // MARK: RequestType typealias Response = Any - init(baseUrl: String = "https://example.com", path: String = "/", method: HTTPMethod = .GET, parameters: Any? = [:], headerFields: [String: String] = [:], interceptURLRequest: @escaping (URLRequest) throws -> URLRequest = { $0 }) { + init(baseUrl: String = "https://example.com", path: String = "/", method: HTTPMethod = .get, parameters: Any? = [:], headerFields: [String: String] = [:], interceptURLRequest: @escaping (URLRequest) throws -> URLRequest = { $0 }) { self.baseUrl = URL(string: baseUrl)! self.path = path self.method = method From 15bb69c8d202a25e9f6e4a0552590349395252c6 Mon Sep 17 00:00:00 2001 From: Syo Ikeda Date: Tue, 23 Aug 2016 23:36:09 +0900 Subject: [PATCH 23/38] [RequestType] Rename interceptURLRequest and interceptObject --- Sources/RequestType.swift | 14 +++++++------- Tests/APIKit/TestComponents/TestRequest.swift | 2 +- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/Sources/RequestType.swift b/Sources/RequestType.swift index 48f6a8aa..b5b67873 100644 --- a/Sources/RequestType.swift +++ b/Sources/RequestType.swift @@ -7,7 +7,7 @@ import Result /// - `var baseUrl: URL` /// - `var method: HTTPMethod` /// - `var path: String` -/// - `func responseFromObject(object: Any, urlResponse: HTTPURLResponse) throws -> Response` +/// - `func response(from object: Any, urlResponse: HTTPURLResponse) throws -> Response` public protocol RequestType { /// The response type associated with the request type. associatedtype Response @@ -46,14 +46,14 @@ public protocol RequestType { /// Intercepts `URLRequest` which is created by `RequestType.buildURLRequest()`. If an error is /// thrown in this method, the result of `Session.sendRequest()` turns `.failure(.requestError(error))`. /// - Throws: `ErrorType` - func interceptURLRequest(_ urlRequest: URLRequest) throws -> URLRequest + func intercept(urlRequest: URLRequest) throws -> URLRequest /// Intercepts response `Any` and `HTTPURLResponse`. If an error is thrown in this method, /// the result of `Session.sendRequest()` turns `.failure(.responseError(error))`. /// The default implementation of this method is provided to throw `RequestError.unacceptableStatusCode` /// if the HTTP status code is not in `200..<300`. /// - Throws: `ErrorType` - func interceptObject(_ object: Any, urlResponse: HTTPURLResponse) throws -> Any + func intercept(object: Any, urlResponse: HTTPURLResponse) throws -> Any /// Build `Response` instance from raw response object. This method is called after /// `interceptObject(:URLResponse:)` if it does not throw any error. @@ -90,11 +90,11 @@ public extension RequestType { return JSONDataParser(readingOptions: []) } - public func interceptURLRequest(_ urlRequest: URLRequest) throws -> URLRequest { + public func intercept(urlRequest: URLRequest) throws -> URLRequest { return urlRequest } - public func interceptObject(_ object: Any, urlResponse: HTTPURLResponse) throws -> Any { + public func intercept(object: Any, urlResponse: HTTPURLResponse) throws -> Any { guard (200..<300).contains(urlResponse.statusCode) else { throw ResponseError.unacceptableStatusCode(urlResponse.statusCode) } @@ -135,14 +135,14 @@ public extension RequestType { urlRequest.setValue(value, forHTTPHeaderField: key) } - return (try interceptURLRequest(urlRequest) as URLRequest) + return (try intercept(urlRequest: urlRequest) as URLRequest) } /// Builds `Response` from response `Data`. /// - Throws: `ResponseError`, `ErrorType` public func parseData(_ data: Data, urlResponse: HTTPURLResponse) throws -> Response { let parsedObject = try dataParser.parseData(data) - let passedObject = try interceptObject(parsedObject, urlResponse: urlResponse) + let passedObject = try intercept(object: parsedObject, urlResponse: urlResponse) return try response(from: passedObject, urlResponse: urlResponse) } } diff --git a/Tests/APIKit/TestComponents/TestRequest.swift b/Tests/APIKit/TestComponents/TestRequest.swift index 549e4161..1ee4292e 100644 --- a/Tests/APIKit/TestComponents/TestRequest.swift +++ b/Tests/APIKit/TestComponents/TestRequest.swift @@ -26,7 +26,7 @@ struct TestRequest: RequestType { let headerFields: [String: String] let interceptURLRequest: (URLRequest) throws -> URLRequest - func interceptURLRequest(_ urlRequest: URLRequest) throws -> URLRequest { + func intercept(urlRequest: URLRequest) throws -> URLRequest { return try interceptURLRequest(urlRequest) } From 9d838ba16dfb99b68007bf7d63cbbb174be023cf Mon Sep 17 00:00:00 2001 From: Syo Ikeda Date: Wed, 24 Aug 2016 02:00:29 +0900 Subject: [PATCH 24/38] Rename some APIs --- .../FormURLEncodedBodyParameters.swift | 2 +- Sources/DataParserType/DataParserType.swift | 2 +- .../DataParserType/FormURLEncodedDataParser.swift | 2 +- Sources/DataParserType/JSONDataParser.swift | 2 +- Sources/DataParserType/StringDataParser.swift | 2 +- Sources/RequestType.swift | 6 +++--- Sources/Serializations/URLEncodedSerialization.swift | 8 ++++---- Sources/Session.swift | 6 +++--- Sources/SessionAdapterType/SessionAdapterType.swift | 4 ++-- Sources/SessionAdapterType/URLSessionAdapter.swift | 12 ++++++------ .../FormURLEncodedBodyParametersTests.swift | 2 +- .../URLEncodedSerializationTests.swift | 10 +++++----- .../FormURLEncodedDataParserTests.swift | 4 ++-- .../APIKit/DataParserType/JSONDataParserTests.swift | 2 +- .../DataParserType/StringDataParserTests.swift | 4 ++-- Tests/APIKit/TestComponents/TestSessionAdapter.swift | 4 ++-- 16 files changed, 36 insertions(+), 36 deletions(-) diff --git a/Sources/BodyParametersType/FormURLEncodedBodyParameters.swift b/Sources/BodyParametersType/FormURLEncodedBodyParameters.swift index d38c1c21..bba787ba 100644 --- a/Sources/BodyParametersType/FormURLEncodedBodyParameters.swift +++ b/Sources/BodyParametersType/FormURLEncodedBodyParameters.swift @@ -24,6 +24,6 @@ public struct FormURLEncodedBodyParameters: BodyParametersType { /// Builds `RequestBodyEntity.data` that represents `form`. /// - Throws: `URLEncodedSerialization.Error` if `URLEncodedSerialization` fails to serialize form object. public func buildEntity() throws -> RequestBodyEntity { - return .data(try URLEncodedSerialization.dataFromObject(form, encoding: encoding)) + return .data(try URLEncodedSerialization.data(from: form, encoding: encoding)) } } diff --git a/Sources/DataParserType/DataParserType.swift b/Sources/DataParserType/DataParserType.swift index 8806958a..8ec5bdea 100644 --- a/Sources/DataParserType/DataParserType.swift +++ b/Sources/DataParserType/DataParserType.swift @@ -7,5 +7,5 @@ public protocol DataParserType { /// Return `Any` that expresses structure of response such as JSON and XML. /// - Throws: `ErrorType` when parser encountered invalid format data. - func parseData(_ data: Data) throws -> Any + func parse(data: Data) throws -> Any } diff --git a/Sources/DataParserType/FormURLEncodedDataParser.swift b/Sources/DataParserType/FormURLEncodedDataParser.swift index a205a014..19f67d1d 100644 --- a/Sources/DataParserType/FormURLEncodedDataParser.swift +++ b/Sources/DataParserType/FormURLEncodedDataParser.swift @@ -23,7 +23,7 @@ public class FormURLEncodedDataParser: DataParserType { /// Return `Any` that expresses structure of response. /// - Throws: `FormURLEncodedDataParser.Error` when the parser fails to initialize `String` from `Data`. - public func parseData(_ data: Data) throws -> Any { + public func parse(data: Data) throws -> Any { guard let string = String(data: data, encoding: encoding) else { throw Error.cannotGetStringFromData(data) } diff --git a/Sources/DataParserType/JSONDataParser.swift b/Sources/DataParserType/JSONDataParser.swift index 62e75990..3b44de54 100644 --- a/Sources/DataParserType/JSONDataParser.swift +++ b/Sources/DataParserType/JSONDataParser.swift @@ -19,7 +19,7 @@ public class JSONDataParser: DataParserType { /// Return `Any` that expresses structure of JSON response. /// - Throws: `NSError` when `JSONSerialization` fails to deserialize `Data` into `Any`. - public func parseData(_ data: Data) throws -> Any { + public func parse(data: Data) throws -> Any { guard data.count > 0 else { return [:] } diff --git a/Sources/DataParserType/StringDataParser.swift b/Sources/DataParserType/StringDataParser.swift index 7a51fe23..5ded7e76 100644 --- a/Sources/DataParserType/StringDataParser.swift +++ b/Sources/DataParserType/StringDataParser.swift @@ -23,7 +23,7 @@ public class StringDataParser: DataParserType { /// Return `String` that converted from `Data`. /// - Throws: `StringDataParser.Error` when the parser fails to initialize `String` from `Data`. - public func parseData(_ data: Data) throws -> Any { + public func parse(data: Data) throws -> Any { guard let string = String(data: data, encoding: encoding) else { throw Error.invalidData(data) } diff --git a/Sources/RequestType.swift b/Sources/RequestType.swift index b5b67873..b96d9846 100644 --- a/Sources/RequestType.swift +++ b/Sources/RequestType.swift @@ -112,7 +112,7 @@ public extension RequestType { var urlRequest = URLRequest(url: url) if let queryParameters = queryParameters, !queryParameters.isEmpty { - components.percentEncodedQuery = URLEncodedSerialization.stringFromDictionary(queryParameters) + components.percentEncodedQuery = URLEncodedSerialization.string(from: queryParameters) } if let bodyParameters = bodyParameters { @@ -140,8 +140,8 @@ public extension RequestType { /// Builds `Response` from response `Data`. /// - Throws: `ResponseError`, `ErrorType` - public func parseData(_ data: Data, urlResponse: HTTPURLResponse) throws -> Response { - let parsedObject = try dataParser.parseData(data) + public func parse(data: Data, urlResponse: HTTPURLResponse) throws -> Response { + let parsedObject = try dataParser.parse(data: data) let passedObject = try intercept(object: parsedObject, urlResponse: urlResponse) return try response(from: passedObject, urlResponse: urlResponse) } diff --git a/Sources/Serializations/URLEncodedSerialization.swift b/Sources/Serializations/URLEncodedSerialization.swift index 7d81a97d..48d000d8 100644 --- a/Sources/Serializations/URLEncodedSerialization.swift +++ b/Sources/Serializations/URLEncodedSerialization.swift @@ -53,7 +53,7 @@ public final class URLEncodedSerialization { /// Returns `[String: String]` that represents urlencoded `Data`. /// - Throws: URLEncodedSerialization.Error - public static func objectFromData(_ data: Data, encoding: String.Encoding) throws -> [String: String] { + public static func object(from data: Data, encoding: String.Encoding) throws -> [String: String] { guard let string = String(data: data, encoding: encoding) else { throw Error.cannotGetStringFromData(data, encoding) } @@ -74,12 +74,12 @@ public final class URLEncodedSerialization { /// Returns urlencoded `Data` from the object. /// - Throws: URLEncodedSerialization.Error - public static func dataFromObject(_ object: Any, encoding: String.Encoding) throws -> Data { + public static func data(from object: Any, encoding: String.Encoding) throws -> Data { guard let dictionary = object as? [String: Any] else { throw Error.cannotCastObjectToDictionary(object) } - let string = stringFromDictionary(dictionary) + let string = self.string(from: dictionary) guard let data = string.data(using: encoding, allowLossyConversion: false) else { throw Error.cannotGetDataFromString(string, encoding) } @@ -88,7 +88,7 @@ public final class URLEncodedSerialization { } /// Returns urlencoded `Data` from the string. - public static func stringFromDictionary(_ dictionary: [String: Any]) -> String { + public static func string(from dictionary: [String: Any]) -> String { let pairs = dictionary.map { key, value -> String in if value is NSNull { return "\(escape(key))" diff --git a/Sources/Session.swift b/Sources/Session.swift index 390aed31..f5452583 100644 --- a/Sources/Session.swift +++ b/Sources/Session.swift @@ -68,7 +68,7 @@ open class Session { return nil } - let task = adapter.createTaskWithURLRequest(urlRequest) { data, urlResponse, error in + let task = adapter.createTask(with: urlRequest) { data, urlResponse, error in let result: Result switch (data, urlResponse, error) { @@ -77,7 +77,7 @@ open class Session { case (let data?, let urlResponse as HTTPURLResponse, _): do { - result = .success(try request.parseData(data as Data, urlResponse: urlResponse)) + result = .success(try request.parse(data: data as Data, urlResponse: urlResponse)) } catch { result = .failure(.responseError(error)) } @@ -101,7 +101,7 @@ open class Session { /// - parameter requestType: The request type to cancel. /// - parameter test: The test closure that determines if a request should be cancelled or not. open func cancelRequest(_ requestType: Request.Type, passingTest test: @escaping (Request) -> Bool = { _ in true }) { - adapter.getTasksWithHandler { [weak self] tasks in + adapter.getTasks { [weak self] tasks in return tasks .filter { task in if let request = self?.requestForTask(task) as Request? { diff --git a/Sources/SessionAdapterType/SessionAdapterType.swift b/Sources/SessionAdapterType/SessionAdapterType.swift index 06b55b36..368a9555 100644 --- a/Sources/SessionAdapterType/SessionAdapterType.swift +++ b/Sources/SessionAdapterType/SessionAdapterType.swift @@ -11,8 +11,8 @@ public protocol SessionTaskType: class { /// with `Session`. public protocol SessionAdapterType { /// Returns instance that conforms to `SessionTaskType`. `handler` must be called after success or failure. - func createTaskWithURLRequest(_ URLRequest: URLRequest, handler: @escaping (Data?, URLResponse?, Error?) -> Void) -> SessionTaskType + func createTask(with URLRequest: URLRequest, handler: @escaping (Data?, URLResponse?, Error?) -> Void) -> SessionTaskType /// Collects tasks from backend networking stack. `handler` must be called after collecting. - func getTasksWithHandler(_ handler: @escaping ([SessionTaskType]) -> Void) + func getTasks(with handler: @escaping ([SessionTaskType]) -> Void) } diff --git a/Sources/SessionAdapterType/URLSessionAdapter.swift b/Sources/SessionAdapterType/URLSessionAdapter.swift index b56712b5..3398f08d 100644 --- a/Sources/SessionAdapterType/URLSessionAdapter.swift +++ b/Sources/SessionAdapterType/URLSessionAdapter.swift @@ -25,7 +25,7 @@ open class URLSessionAdapter: NSObject, SessionAdapterType, URLSessionDelegate, } /// Creates `URLSessionDataTask` instance using `dataTaskWithRequest(_:completionHandler:)`. - open func createTaskWithURLRequest(_ URLRequest: URLRequest, handler: @escaping (Data?, URLResponse?, Error?) -> Void) -> SessionTaskType { + open func createTask(with URLRequest: URLRequest, handler: @escaping (Data?, URLResponse?, Error?) -> Void) -> SessionTaskType { let task = urlSession.dataTask(with: URLRequest) setBuffer(NSMutableData(), forTask: task) @@ -37,7 +37,7 @@ open class URLSessionAdapter: NSObject, SessionAdapterType, URLSessionDelegate, } /// Aggregates `URLSessionTask` instances in `URLSession` using `getTasksWithCompletionHandler(_:)`. - open func getTasksWithHandler(_ handler: @escaping ([SessionTaskType]) -> Void) { + open func getTasks(with handler: @escaping ([SessionTaskType]) -> Void) { urlSession.getTasksWithCompletionHandler { dataTasks, uploadTasks, downloadTasks in let allTasks = dataTasks as [URLSessionTask] + uploadTasks as [URLSessionTask] @@ -51,7 +51,7 @@ open class URLSessionAdapter: NSObject, SessionAdapterType, URLSessionDelegate, objc_setAssociatedObject(task, &dataTaskResponseBufferKey, buffer, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } - private func bufferForTask(_ task: URLSessionTask) -> NSMutableData? { + private func buffer(for task: URLSessionTask) -> NSMutableData? { return objc_getAssociatedObject(task, &dataTaskResponseBufferKey) as? NSMutableData } @@ -59,17 +59,17 @@ open class URLSessionAdapter: NSObject, SessionAdapterType, URLSessionDelegate, objc_setAssociatedObject(task, &taskAssociatedObjectCompletionHandlerKey, Box(handler), .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } - private func handlerForTask(_ task: URLSessionTask) -> ((Data?, URLResponse?, Error?) -> Void)? { + private func handler(for task: URLSessionTask) -> ((Data?, URLResponse?, Error?) -> Void)? { return (objc_getAssociatedObject(task, &taskAssociatedObjectCompletionHandlerKey) as? Box<(Data?, URLResponse?, Error?) -> Void>)?.value } // MARK: URLSessionTaskDelegate open func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { - handlerForTask(task)?(bufferForTask(task) as Data?, task.response, error) + handler(for: task)?(buffer(for: task) as Data?, task.response, error) } // MARK: URLSessionDataDelegate open func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) { - bufferForTask(dataTask)?.append(data) + buffer(for: dataTask)?.append(data) } } diff --git a/Tests/APIKit/BodyParametersType/FormURLEncodedBodyParametersTests.swift b/Tests/APIKit/BodyParametersType/FormURLEncodedBodyParametersTests.swift index 803ce218..3afa7262 100644 --- a/Tests/APIKit/BodyParametersType/FormURLEncodedBodyParametersTests.swift +++ b/Tests/APIKit/BodyParametersType/FormURLEncodedBodyParametersTests.swift @@ -14,7 +14,7 @@ class FormURLEncodedBodyParametersTests: XCTestCase { return } - let createdObject = try URLEncodedSerialization.objectFromData(data, encoding: .utf8) + let createdObject = try URLEncodedSerialization.object(from: data, encoding: .utf8) XCTAssertEqual(createdObject["foo"], "1") XCTAssertEqual(createdObject["bar"], "2") XCTAssertEqual(createdObject["baz"], "3") diff --git a/Tests/APIKit/BodyParametersType/URLEncodedSerializationTests.swift b/Tests/APIKit/BodyParametersType/URLEncodedSerializationTests.swift index 5cdb0983..89702e4d 100644 --- a/Tests/APIKit/BodyParametersType/URLEncodedSerializationTests.swift +++ b/Tests/APIKit/BodyParametersType/URLEncodedSerializationTests.swift @@ -6,7 +6,7 @@ class URLEncodedSerializationTests: XCTestCase { // MARK: NSData -> Any func testObjectFromData() { let data = "key1=value1&key2=value2".data(using: .utf8)! - let object = try? URLEncodedSerialization.objectFromData(data, encoding: .utf8) + let object = try? URLEncodedSerialization.object(from: data, encoding: .utf8) XCTAssertEqual(object?["key1"], "value1") XCTAssertEqual(object?["key2"], "value2") } @@ -16,7 +16,7 @@ class URLEncodedSerializationTests: XCTestCase { do { let data = string.data(using: .utf8)! - try _ = URLEncodedSerialization.objectFromData(data, encoding: .utf8) + try _ = URLEncodedSerialization.object(from: data, encoding: .utf8) XCTFail() } catch { guard let error = error as? URLEncodedSerialization.Error, @@ -34,7 +34,7 @@ class URLEncodedSerializationTests: XCTestCase { let data = Data(bytes: &bytes, count: bytes.count) do { - try _ = URLEncodedSerialization.objectFromData(data, encoding: .utf8) + try _ = URLEncodedSerialization.object(from: data, encoding: .utf8) XCTFail() } catch { guard let error = error as? URLEncodedSerialization.Error, @@ -51,7 +51,7 @@ class URLEncodedSerializationTests: XCTestCase { // MARK: Any -> NSData func testDataFromObject() { let object = ["hey": "yo"] as Any - let data = try? URLEncodedSerialization.dataFromObject(object, encoding: .utf8) + let data = try? URLEncodedSerialization.data(from: object, encoding: .utf8) let string = data.flatMap { String(data: $0, encoding: .utf8) } XCTAssertEqual(string, "hey=yo") } @@ -60,7 +60,7 @@ class URLEncodedSerializationTests: XCTestCase { let dictionaries = [["hey": "yo"]] as Any do { - try _ = URLEncodedSerialization.dataFromObject(dictionaries, encoding: .utf8) + try _ = URLEncodedSerialization.data(from: dictionaries, encoding: .utf8) XCTFail() } catch { guard let error = error as? URLEncodedSerialization.Error, diff --git a/Tests/APIKit/DataParserType/FormURLEncodedDataParserTests.swift b/Tests/APIKit/DataParserType/FormURLEncodedDataParserTests.swift index 4c46ea1d..8bf66a77 100644 --- a/Tests/APIKit/DataParserType/FormURLEncodedDataParserTests.swift +++ b/Tests/APIKit/DataParserType/FormURLEncodedDataParserTests.swift @@ -14,7 +14,7 @@ class FormURLEncodedDataParserTests: XCTestCase { let parser = FormURLEncodedDataParser(encoding: .utf8) do { - let object = try parser.parseData(data) + let object = try parser.parse(data: data) let dictionary = object as? [String: String] XCTAssertEqual(dictionary?["foo"], "1") XCTAssertEqual(dictionary?["bar"], "2") @@ -30,7 +30,7 @@ class FormURLEncodedDataParserTests: XCTestCase { let parser = FormURLEncodedDataParser(encoding: .utf8) do { - try _ = parser.parseData(data) + try _ = parser.parse(data: data) XCTFail() } catch { guard let error = error as? FormURLEncodedDataParser.Error, diff --git a/Tests/APIKit/DataParserType/JSONDataParserTests.swift b/Tests/APIKit/DataParserType/JSONDataParserTests.swift index ee417d6a..e7faaca4 100644 --- a/Tests/APIKit/DataParserType/JSONDataParserTests.swift +++ b/Tests/APIKit/DataParserType/JSONDataParserTests.swift @@ -14,7 +14,7 @@ class JSONDataParserTests: XCTestCase { let parser = JSONDataParser(readingOptions: []) do { - let object = try parser.parseData(data) + let object = try parser.parse(data: data) let dictionary = object as? [String: Int] XCTAssertEqual(dictionary?["foo"], 1) XCTAssertEqual(dictionary?["bar"], 2) diff --git a/Tests/APIKit/DataParserType/StringDataParserTests.swift b/Tests/APIKit/DataParserType/StringDataParserTests.swift index bc104476..0dc0255a 100644 --- a/Tests/APIKit/DataParserType/StringDataParserTests.swift +++ b/Tests/APIKit/DataParserType/StringDataParserTests.swift @@ -14,7 +14,7 @@ class StringDataParserTests: XCTestCase { let parser = StringDataParser(encoding: .utf8) do { - let object = try parser.parseData(data) + let object = try parser.parse(data: data) XCTAssertEqual(object as? String, string) } catch { XCTFail() @@ -27,7 +27,7 @@ class StringDataParserTests: XCTestCase { let parser = StringDataParser(encoding: .utf8) do { - try _ = parser.parseData(data) + try _ = parser.parse(data: data) XCTFail() } catch { guard let error = error as? StringDataParser.Error, diff --git a/Tests/APIKit/TestComponents/TestSessionAdapter.swift b/Tests/APIKit/TestComponents/TestSessionAdapter.swift index 3e0de50c..52da166f 100644 --- a/Tests/APIKit/TestComponents/TestSessionAdapter.swift +++ b/Tests/APIKit/TestComponents/TestSessionAdapter.swift @@ -49,14 +49,14 @@ class TestSessionAdapter: SessionAdapterType { tasks = [] } - func createTaskWithURLRequest(_ URLRequest: URLRequest, handler: @escaping (Data?, URLResponse?, Swift.Error?) -> Void) -> SessionTaskType { + func createTask(with URLRequest: URLRequest, handler: @escaping (Data?, URLResponse?, Swift.Error?) -> Void) -> SessionTaskType { let task = TestSessionTask(handler: handler) tasks.append(task) return task } - func getTasksWithHandler(_ handler: @escaping ([SessionTaskType]) -> Void) { + func getTasks(with handler: @escaping ([SessionTaskType]) -> Void) { handler(tasks.map { $0 }) } } From dfa5000eeb887530dbfb2d0ab9b752808cdee404 Mon Sep 17 00:00:00 2001 From: Syo Ikeda Date: Wed, 24 Aug 2016 02:07:56 +0900 Subject: [PATCH 25/38] Fix documentation --- Sources/BodyParametersType/BodyParametersType.swift | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Sources/BodyParametersType/BodyParametersType.swift b/Sources/BodyParametersType/BodyParametersType.swift index 14c0d32e..9b73aa0c 100644 --- a/Sources/BodyParametersType/BodyParametersType.swift +++ b/Sources/BodyParametersType/BodyParametersType.swift @@ -2,10 +2,10 @@ import Foundation /// `RequestBodyEntity` represents entity of HTTP body. public enum RequestBodyEntity { - /// Expresses entity as `Data`. The associated value will be set to `URLRequest.HTTPBody`. + /// Expresses entity as `Data`. The associated value will be set to `URLRequest.httpBody`. case data(Data) - /// Expresses entity as `InputStream`. The associated value will be set to `URLRequest.HTTPBodyStream`. + /// Expresses entity as `InputStream`. The associated value will be set to `URLRequest.httpBodyStream`. case inputStream(InputStream) } From 4d609328dd4ea4b1e0693ab22d5d1161c712c5f3 Mon Sep 17 00:00:00 2001 From: Syo Ikeda Date: Wed, 24 Aug 2016 02:21:11 +0900 Subject: [PATCH 26/38] Box can be removed thanks to SE-0116 --- APIKit.xcodeproj/project.pbxproj | 4 ---- Sources/Box.swift | 9 --------- Sources/Session.swift | 4 ++-- Sources/SessionAdapterType/URLSessionAdapter.swift | 6 +++--- 4 files changed, 5 insertions(+), 18 deletions(-) delete mode 100644 Sources/Box.swift diff --git a/APIKit.xcodeproj/project.pbxproj b/APIKit.xcodeproj/project.pbxproj index 2d903a10..d40b5eff 100644 --- a/APIKit.xcodeproj/project.pbxproj +++ b/APIKit.xcodeproj/project.pbxproj @@ -46,7 +46,6 @@ 7FA19A421C9CBF2A005D25AE /* ResponseError.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7FA19A3F1C9CBF2A005D25AE /* ResponseError.swift */; }; 7FA19A431C9CBF2A005D25AE /* SessionTaskError.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7FA19A401C9CBF2A005D25AE /* SessionTaskError.swift */; }; 7FA19A461C9CC9D0005D25AE /* DataParserType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7FA19A451C9CC9D0005D25AE /* DataParserType.swift */; }; - 7FAC40341C8F2C900098C4B2 /* Box.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7FAC40331C8F2C900098C4B2 /* Box.swift */; }; 7FAC64AE1CDC7ADE00F1BB45 /* AbstractInputStream.m in Sources */ = {isa = PBXBuildFile; fileRef = 7FAC64AC1CDC7ADE00F1BB45 /* AbstractInputStream.m */; }; 7FB650DF1CEA0E6B00366992 /* StringDataParser.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7FB650DE1CEA0E6B00366992 /* StringDataParser.swift */; }; 7FB650E11CEA0F3D00366992 /* StringDataParserTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7FB650E01CEA0F3D00366992 /* StringDataParserTests.swift */; }; @@ -122,7 +121,6 @@ 7FA19A3F1C9CBF2A005D25AE /* ResponseError.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ResponseError.swift; sourceTree = ""; }; 7FA19A401C9CBF2A005D25AE /* SessionTaskError.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SessionTaskError.swift; sourceTree = ""; }; 7FA19A451C9CC9D0005D25AE /* DataParserType.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DataParserType.swift; sourceTree = ""; }; - 7FAC40331C8F2C900098C4B2 /* Box.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Box.swift; sourceTree = ""; }; 7FAC64AC1CDC7ADE00F1BB45 /* AbstractInputStream.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AbstractInputStream.m; sourceTree = ""; }; 7FB650DE1CEA0E6B00366992 /* StringDataParser.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StringDataParser.swift; sourceTree = ""; }; 7FB650E01CEA0F3D00366992 /* StringDataParserTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StringDataParserTests.swift; sourceTree = ""; }; @@ -244,7 +242,6 @@ 7F7E8F101C8AD4B1008A13A9 /* RequestType.swift */, 7F7E8F0C1C8AD4B1008A13A9 /* HTTPMethod.swift */, 7F10D8ED1CD5CF8D00722F66 /* CallbackQueue.swift */, - 7FAC40331C8F2C900098C4B2 /* Box.swift */, 7F85FB8B1C9D317300CEE132 /* SessionAdapterType */, 7F18BD0D1C972C38003A31DF /* BodyParametersType */, 7FA19A441C9CC9A2005D25AE /* DataParserType */, @@ -453,7 +450,6 @@ 7F7E8F1C1C8AD4B1008A13A9 /* Session.swift in Sources */, 7F18BD0F1C972C38003A31DF /* BodyParametersType.swift in Sources */, 7F2A15BD1CEB5F67009A12A2 /* Data+InputStream.swift in Sources */, - 7FAC40341C8F2C900098C4B2 /* Box.swift in Sources */, 7FB650DF1CEA0E6B00366992 /* StringDataParser.swift in Sources */, 7F18BD131C972E5A003A31DF /* FormURLEncodedBodyParameters.swift in Sources */, 7FA19A461C9CC9D0005D25AE /* DataParserType.swift in Sources */, diff --git a/Sources/Box.swift b/Sources/Box.swift deleted file mode 100644 index baacebee..00000000 --- a/Sources/Box.swift +++ /dev/null @@ -1,9 +0,0 @@ -import Foundation - -internal final class Box { - let value: T - - init(_ value: T) { - self.value = value - } -} diff --git a/Sources/Session.swift b/Sources/Session.swift index f5452583..a09d7919 100644 --- a/Sources/Session.swift +++ b/Sources/Session.swift @@ -115,10 +115,10 @@ open class Session { } private func setRequest(_ request: Request, forTask task: SessionTaskType) { - objc_setAssociatedObject(task, &taskRequestKey, Box(request), .OBJC_ASSOCIATION_RETAIN_NONATOMIC) + objc_setAssociatedObject(task, &taskRequestKey, request, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } private func requestForTask(_ task: SessionTaskType) -> Request? { - return (objc_getAssociatedObject(task, &taskRequestKey) as? Box)?.value + return objc_getAssociatedObject(task, &taskRequestKey) as? Request } } diff --git a/Sources/SessionAdapterType/URLSessionAdapter.swift b/Sources/SessionAdapterType/URLSessionAdapter.swift index 3398f08d..3abc3a98 100644 --- a/Sources/SessionAdapterType/URLSessionAdapter.swift +++ b/Sources/SessionAdapterType/URLSessionAdapter.swift @@ -55,12 +55,12 @@ open class URLSessionAdapter: NSObject, SessionAdapterType, URLSessionDelegate, return objc_getAssociatedObject(task, &dataTaskResponseBufferKey) as? NSMutableData } - private func setHandler(_ handler: (Data?, URLResponse?, Error?) -> Void, forTask task: URLSessionTask) { - objc_setAssociatedObject(task, &taskAssociatedObjectCompletionHandlerKey, Box(handler), .OBJC_ASSOCIATION_RETAIN_NONATOMIC) + private func setHandler(_ handler: @escaping (Data?, URLResponse?, Error?) -> Void, forTask task: URLSessionTask) { + objc_setAssociatedObject(task, &taskAssociatedObjectCompletionHandlerKey, handler as Any, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } private func handler(for task: URLSessionTask) -> ((Data?, URLResponse?, Error?) -> Void)? { - return (objc_getAssociatedObject(task, &taskAssociatedObjectCompletionHandlerKey) as? Box<(Data?, URLResponse?, Error?) -> Void>)?.value + return objc_getAssociatedObject(task, &taskAssociatedObjectCompletionHandlerKey) as? (Data?, URLResponse?, Error?) -> Void } // MARK: URLSessionTaskDelegate From 0b5c2af2e3a9e17d201f2b17a1b78445b360ce7c Mon Sep 17 00:00:00 2001 From: Syo Ikeda Date: Thu, 8 Sep 2016 06:27:35 +0900 Subject: [PATCH 27/38] Fix Xcode 8 GM compatibility --- Cartfile.private | 2 +- Cartfile.resolved | 2 +- Carthage/Checkouts/OHHTTPStubs | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/Cartfile.private b/Cartfile.private index 5649a9f9..f472f643 100644 --- a/Cartfile.private +++ b/Cartfile.private @@ -1 +1 @@ -github "AliSoftware/OHHTTPStubs" "5.2.0-swift3" +github "AliSoftware/OHHTTPStubs" "xcode8-gm" diff --git a/Cartfile.resolved b/Cartfile.resolved index 8fb10e7d..e2790c46 100644 --- a/Cartfile.resolved +++ b/Cartfile.resolved @@ -1,2 +1,2 @@ -github "AliSoftware/OHHTTPStubs" "5.2.0-swift3" +github "AliSoftware/OHHTTPStubs" "1a6e3d994d7d7a1bae6ae3eb255fc34eb43025e1" github "antitypical/Result" "3.0.0-alpha.3" diff --git a/Carthage/Checkouts/OHHTTPStubs b/Carthage/Checkouts/OHHTTPStubs index 5198de9d..1a6e3d99 160000 --- a/Carthage/Checkouts/OHHTTPStubs +++ b/Carthage/Checkouts/OHHTTPStubs @@ -1 +1 @@ -Subproject commit 5198de9d0ab671b03a3c67540a6e983737c8eddc +Subproject commit 1a6e3d994d7d7a1bae6ae3eb255fc34eb43025e1 From 662bfca2c09cac333f58d230fe93f46ea003c3ec Mon Sep 17 00:00:00 2001 From: Syo Ikeda Date: Thu, 8 Sep 2016 06:28:26 +0900 Subject: [PATCH 28/38] Update Result to 3.0.0-alpha.4 --- Cartfile | 2 +- Cartfile.resolved | 2 +- Carthage/Checkouts/Result | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/Cartfile b/Cartfile index 32737a64..e4382737 100644 --- a/Cartfile +++ b/Cartfile @@ -1 +1 @@ -github "antitypical/Result" "3.0.0-alpha.3" +github "antitypical/Result" "3.0.0-alpha.4" diff --git a/Cartfile.resolved b/Cartfile.resolved index e2790c46..c5f9203a 100644 --- a/Cartfile.resolved +++ b/Cartfile.resolved @@ -1,2 +1,2 @@ github "AliSoftware/OHHTTPStubs" "1a6e3d994d7d7a1bae6ae3eb255fc34eb43025e1" -github "antitypical/Result" "3.0.0-alpha.3" +github "antitypical/Result" "3.0.0-alpha.4" diff --git a/Carthage/Checkouts/Result b/Carthage/Checkouts/Result index d78cac38..cc1699db 160000 --- a/Carthage/Checkouts/Result +++ b/Carthage/Checkouts/Result @@ -1 +1 @@ -Subproject commit d78cac38657de99d85f8f1770b290d039721ef27 +Subproject commit cc1699dbd812c71bee7c44c8cbd75497713bc279 From 0b0ff9881faf65502ef63551fd966b5874b92fe3 Mon Sep 17 00:00:00 2001 From: Syo Ikeda Date: Wed, 14 Sep 2016 21:57:01 +0900 Subject: [PATCH 29/38] Update OHHTTPStubs --- Cartfile.private | 2 +- Cartfile.resolved | 2 +- Carthage/Checkouts/OHHTTPStubs | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/Cartfile.private b/Cartfile.private index f472f643..c77bf5c5 100644 --- a/Cartfile.private +++ b/Cartfile.private @@ -1 +1 @@ -github "AliSoftware/OHHTTPStubs" "xcode8-gm" +github "AliSoftware/OHHTTPStubs" "5.2.1-swift3" diff --git a/Cartfile.resolved b/Cartfile.resolved index c5f9203a..4d347648 100644 --- a/Cartfile.resolved +++ b/Cartfile.resolved @@ -1,2 +1,2 @@ -github "AliSoftware/OHHTTPStubs" "1a6e3d994d7d7a1bae6ae3eb255fc34eb43025e1" +github "AliSoftware/OHHTTPStubs" "5.2.1-swift3" github "antitypical/Result" "3.0.0-alpha.4" diff --git a/Carthage/Checkouts/OHHTTPStubs b/Carthage/Checkouts/OHHTTPStubs index 1a6e3d99..624d5161 160000 --- a/Carthage/Checkouts/OHHTTPStubs +++ b/Carthage/Checkouts/OHHTTPStubs @@ -1 +1 @@ -Subproject commit 1a6e3d994d7d7a1bae6ae3eb255fc34eb43025e1 +Subproject commit 624d51619bc88144015c2b275e761b359ae5ecb3 From 37885fb6406f34198d031d0b7aeb6ed998d64953 Mon Sep 17 00:00:00 2001 From: Syo Ikeda Date: Wed, 14 Sep 2016 21:59:34 +0900 Subject: [PATCH 30/38] Update Result to 3.0.0 --- Cartfile | 2 +- Cartfile.resolved | 2 +- Carthage/Checkouts/Result | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/Cartfile b/Cartfile index e4382737..32a661fc 100644 --- a/Cartfile +++ b/Cartfile @@ -1 +1 @@ -github "antitypical/Result" "3.0.0-alpha.4" +github "antitypical/Result" ~> 3.0 diff --git a/Cartfile.resolved b/Cartfile.resolved index 4d347648..06a1ddec 100644 --- a/Cartfile.resolved +++ b/Cartfile.resolved @@ -1,2 +1,2 @@ github "AliSoftware/OHHTTPStubs" "5.2.1-swift3" -github "antitypical/Result" "3.0.0-alpha.4" +github "antitypical/Result" "3.0.0" diff --git a/Carthage/Checkouts/Result b/Carthage/Checkouts/Result index cc1699db..df233a8d 160000 --- a/Carthage/Checkouts/Result +++ b/Carthage/Checkouts/Result @@ -1 +1 @@ -Subproject commit cc1699dbd812c71bee7c44c8cbd75497713bc279 +Subproject commit df233a8d23a545153d5b5de13b1ac8db2503f088 From 28b19ddcc0906cdfe65400a2f730b5723357b848 Mon Sep 17 00:00:00 2001 From: Syo Ikeda Date: Fri, 16 Sep 2016 14:11:38 +0900 Subject: [PATCH 31/38] Rename RequestType to Request --- APIKit.xcodeproj/project.pbxproj | 16 +++++++-------- Demo.playground/Contents.swift | 6 +++--- Sources/Error/RequestError.swift | 6 +++--- Sources/Error/ResponseError.swift | 2 +- Sources/Error/SessionTaskError.swift | 2 +- Sources/{RequestType.swift => Request.swift} | 8 ++++---- Sources/Session.swift | 20 +++++++++---------- ...uestTypeTests.swift => RequestTests.swift} | 2 +- Tests/APIKit/SessionTests.swift | 8 ++++---- Tests/APIKit/TestComponents/TestRequest.swift | 4 ++-- 10 files changed, 37 insertions(+), 37 deletions(-) rename Sources/{RequestType.swift => Request.swift} (96%) rename Tests/APIKit/{RequestTypeTests.swift => RequestTests.swift} (99%) diff --git a/APIKit.xcodeproj/project.pbxproj b/APIKit.xcodeproj/project.pbxproj index d40b5eff..e8ce3d08 100644 --- a/APIKit.xcodeproj/project.pbxproj +++ b/APIKit.xcodeproj/project.pbxproj @@ -12,7 +12,7 @@ 141F12321C1C9AC70026D415 /* OHHTTPStubs.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = CD51152D1B1FFCC700514240 /* OHHTTPStubs.framework */; }; 141F12361C1C9AC70026D415 /* Result.framework in Copy Frameworks */ = {isa = PBXBuildFile; fileRef = CD5115241B1FFBA900514240 /* Result.framework */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; }; 141F12371C1C9AC70026D415 /* OHHTTPStubs.framework in Copy Frameworks */ = {isa = PBXBuildFile; fileRef = CD51152D1B1FFCC700514240 /* OHHTTPStubs.framework */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; }; - 7F09BF931C8AE8DB00F4A59A /* RequestTypeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7F09BF8D1C8AE8DB00F4A59A /* RequestTypeTests.swift */; }; + 7F09BF931C8AE8DB00F4A59A /* RequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7F09BF8D1C8AE8DB00F4A59A /* RequestTests.swift */; }; 7F10D8EE1CD5CF8D00722F66 /* CallbackQueue.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7F10D8ED1CD5CF8D00722F66 /* CallbackQueue.swift */; }; 7F10D8F01CD5D10100722F66 /* SessionCallbackQueueTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7F10D8EF1CD5D10100722F66 /* SessionCallbackQueueTests.swift */; }; 7F18BD0F1C972C38003A31DF /* BodyParametersType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7F18BD0E1C972C38003A31DF /* BodyParametersType.swift */; }; @@ -25,7 +25,7 @@ 7F2A537C1CF5D55D000353F0 /* URLEncodedSerializationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7F2A537B1CF5D55D000353F0 /* URLEncodedSerializationTests.swift */; }; 7F7E8F151C8AD4B1008A13A9 /* APIKit.h in Headers */ = {isa = PBXBuildFile; fileRef = 7F7E8F0B1C8AD4B1008A13A9 /* APIKit.h */; settings = {ATTRIBUTES = (Public, ); }; }; 7F7E8F161C8AD4B1008A13A9 /* HTTPMethod.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7F7E8F0C1C8AD4B1008A13A9 /* HTTPMethod.swift */; }; - 7F7E8F1A1C8AD4B1008A13A9 /* RequestType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7F7E8F101C8AD4B1008A13A9 /* RequestType.swift */; }; + 7F7E8F1A1C8AD4B1008A13A9 /* Request.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7F7E8F101C8AD4B1008A13A9 /* Request.swift */; }; 7F7E8F1C1C8AD4B1008A13A9 /* Session.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7F7E8F121C8AD4B1008A13A9 /* Session.swift */; }; 7F85FB801C9CF12600CEE132 /* JSONDataParser.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7F85FB7F1C9CF12600CEE132 /* JSONDataParser.swift */; }; 7F85FB831C9CF25D00CEE132 /* JSONDataParserTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7F85FB821C9CF25D00CEE132 /* JSONDataParserTests.swift */; }; @@ -85,7 +85,7 @@ 141F123F1C1C9EA30026D415 /* APIKit.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = APIKit.xcconfig; path = Configurations/APIKit.xcconfig; sourceTree = ""; }; 141F12401C1C9EA30026D415 /* Tests.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = Tests.xcconfig; path = Configurations/Tests.xcconfig; sourceTree = ""; }; 7F09BF8B1C8AE8DB00F4A59A /* Info.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; - 7F09BF8D1C8AE8DB00F4A59A /* RequestTypeTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RequestTypeTests.swift; sourceTree = ""; }; + 7F09BF8D1C8AE8DB00F4A59A /* RequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RequestTests.swift; sourceTree = ""; }; 7F10D8ED1CD5CF8D00722F66 /* CallbackQueue.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CallbackQueue.swift; sourceTree = ""; }; 7F10D8EF1CD5D10100722F66 /* SessionCallbackQueueTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SessionCallbackQueueTests.swift; sourceTree = ""; }; 7F18BD0E1C972C38003A31DF /* BodyParametersType.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = BodyParametersType.swift; sourceTree = ""; }; @@ -99,7 +99,7 @@ 7F7E8F0B1C8AD4B1008A13A9 /* APIKit.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = APIKit.h; sourceTree = ""; }; 7F7E8F0C1C8AD4B1008A13A9 /* HTTPMethod.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = HTTPMethod.swift; sourceTree = ""; }; 7F7E8F0D1C8AD4B1008A13A9 /* Info.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; - 7F7E8F101C8AD4B1008A13A9 /* RequestType.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RequestType.swift; sourceTree = ""; }; + 7F7E8F101C8AD4B1008A13A9 /* Request.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Request.swift; sourceTree = ""; }; 7F7E8F121C8AD4B1008A13A9 /* Session.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Session.swift; sourceTree = ""; }; 7F85FB7F1C9CF12600CEE132 /* JSONDataParser.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = JSONDataParser.swift; sourceTree = ""; }; 7F85FB821C9CF25D00CEE132 /* JSONDataParserTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = JSONDataParserTests.swift; sourceTree = ""; }; @@ -174,7 +174,7 @@ children = ( 7F85FB9E1C9D3F0B00CEE132 /* SessionTests.swift */, 7F10D8EF1CD5D10100722F66 /* SessionCallbackQueueTests.swift */, - 7F09BF8D1C8AE8DB00F4A59A /* RequestTypeTests.swift */, + 7F09BF8D1C8AE8DB00F4A59A /* RequestTests.swift */, 7F85FB901C9D335F00CEE132 /* SessionAdapterType */, 7F85FB811C9CF24900CEE132 /* DataParserType */, 7FA19A361C98642F005D25AE /* BodyParametersType */, @@ -239,7 +239,7 @@ isa = PBXGroup; children = ( 7F7E8F121C8AD4B1008A13A9 /* Session.swift */, - 7F7E8F101C8AD4B1008A13A9 /* RequestType.swift */, + 7F7E8F101C8AD4B1008A13A9 /* Request.swift */, 7F7E8F0C1C8AD4B1008A13A9 /* HTTPMethod.swift */, 7F10D8ED1CD5CF8D00722F66 /* CallbackQueue.swift */, 7F85FB8B1C9D317300CEE132 /* SessionAdapterType */, @@ -443,7 +443,7 @@ isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( - 7F7E8F1A1C8AD4B1008A13A9 /* RequestType.swift in Sources */, + 7F7E8F1A1C8AD4B1008A13A9 /* Request.swift in Sources */, 7FA19A331C985CEC005D25AE /* MultipartFormDataBodyParameters.swift in Sources */, 7F85FB871C9CF47300CEE132 /* FormURLEncodedDataParser.swift in Sources */, 7FA19A431C9CBF2A005D25AE /* SessionTaskError.swift in Sources */, @@ -480,7 +480,7 @@ 7F85FB9F1C9D3F0B00CEE132 /* SessionTests.swift in Sources */, 7F85FB921C9D336D00CEE132 /* URLSessionAdapterTests.swift in Sources */, 7F2A537C1CF5D55D000353F0 /* URLEncodedSerializationTests.swift in Sources */, - 7F09BF931C8AE8DB00F4A59A /* RequestTypeTests.swift in Sources */, + 7F09BF931C8AE8DB00F4A59A /* RequestTests.swift in Sources */, 7FA19A3B1C98642F005D25AE /* JSONBodyParametersTests.swift in Sources */, 7F2001D71CF49F3000C5D0EE /* URLSessionAdapterSubclassTests.swift in Sources */, 7F85FB9A1C9D3DA700CEE132 /* TestRequest.swift in Sources */, diff --git a/Demo.playground/Contents.swift b/Demo.playground/Contents.swift index f4a73188..ef869984 100644 --- a/Demo.playground/Contents.swift +++ b/Demo.playground/Contents.swift @@ -5,11 +5,11 @@ import APIKit PlaygroundPage.current.needsIndefiniteExecution = true //: Step 1: Define request protocol -protocol GitHubRequestType: RequestType { +protocol GitHubRequest: Request { } -extension GitHubRequestType { +extension GitHubRequest { var baseUrl: URL { return URL(string: "https://api.github.com")! } @@ -36,7 +36,7 @@ struct RateLimit { //: Step 3: Define request type conforming to created request protocol // https://developer.github.com/v3/rate_limit/ -struct GetRateLimitRequest: GitHubRequestType { +struct GetRateLimitRequest: GitHubRequest { typealias Response = RateLimit var method: HTTPMethod { diff --git a/Sources/Error/RequestError.swift b/Sources/Error/RequestError.swift index 06380dde..278cb5bd 100644 --- a/Sources/Error/RequestError.swift +++ b/Sources/Error/RequestError.swift @@ -1,10 +1,10 @@ import Foundation -/// `RequestError` represents a common error that occurs while building `URLRequest` from `RequestType`. +/// `RequestError` represents a common error that occurs while building `URLRequest` from `Request`. public enum RequestError: Error { - /// Indicates `baseUrl` of a type that conforms `RequestType` is invalid. + /// Indicates `baseUrl` of a type that conforms `Request` is invalid. case invalidBaseURL(URL) - /// Indicates `URLRequest` built by `RequestType.buildURLRequest` is unexpected. + /// Indicates `URLRequest` built by `Request.buildURLRequest` is unexpected. case unexpectedURLRequest(URLRequest) } diff --git a/Sources/Error/ResponseError.swift b/Sources/Error/ResponseError.swift index e2e61859..50efdecd 100644 --- a/Sources/Error/ResponseError.swift +++ b/Sources/Error/ResponseError.swift @@ -1,6 +1,6 @@ import Foundation -/// `ResponseError` represents a common error that occurs while getting `RequestType.Response` +/// `ResponseError` represents a common error that occurs while getting `Request.Response` /// from raw result tuple `(Data?, URLResponse?, Error?)`. public enum ResponseError: Error { /// Indicates the session adapter returned `URLResponse` that fails to down-cast to `HTTPURLResponse`. diff --git a/Sources/Error/SessionTaskError.swift b/Sources/Error/SessionTaskError.swift index ed46880e..cb9eb929 100644 --- a/Sources/Error/SessionTaskError.swift +++ b/Sources/Error/SessionTaskError.swift @@ -8,6 +8,6 @@ public enum SessionTaskError: Error { /// Error while creating `URLReqeust` from `Request`. case requestError(Error) - /// Error while creating `RequestType.Response` from `(Data, URLResponse)`. + /// Error while creating `Request.Response` from `(Data, URLResponse)`. case responseError(Error) } diff --git a/Sources/RequestType.swift b/Sources/Request.swift similarity index 96% rename from Sources/RequestType.swift rename to Sources/Request.swift index b96d9846..63408d1e 100644 --- a/Sources/RequestType.swift +++ b/Sources/Request.swift @@ -1,14 +1,14 @@ import Foundation import Result -/// `RequestType` protocol represents a request for Web API. +/// `Request` protocol represents a request for Web API. /// Following 5 items must be implemented. /// - `typealias Response` /// - `var baseUrl: URL` /// - `var method: HTTPMethod` /// - `var path: String` /// - `func response(from object: Any, urlResponse: HTTPURLResponse) throws -> Response` -public protocol RequestType { +public protocol Request { /// The response type associated with the request type. associatedtype Response @@ -43,7 +43,7 @@ public protocol RequestType { /// The parser object that states `Content-Type` to accept and parses response body. var dataParser: DataParserType { get } - /// Intercepts `URLRequest` which is created by `RequestType.buildURLRequest()`. If an error is + /// Intercepts `URLRequest` which is created by `Request.buildURLRequest()`. If an error is /// thrown in this method, the result of `Session.sendRequest()` turns `.failure(.requestError(error))`. /// - Throws: `ErrorType` func intercept(urlRequest: URLRequest) throws -> URLRequest @@ -61,7 +61,7 @@ public protocol RequestType { func response(from object: Any, urlResponse: HTTPURLResponse) throws -> Response } -public extension RequestType { +public extension Request { public var parameters: Any? { return nil } diff --git a/Sources/Session.swift b/Sources/Session.swift index a09d7919..8f7f81fe 100644 --- a/Sources/Session.swift +++ b/Sources/Session.swift @@ -37,17 +37,17 @@ open class Session { /// - parameter handler: The closure that receives result of the request. /// - returns: The new session task. @discardableResult - open class func sendRequest(_ request: Request, callbackQueue: CallbackQueue? = nil, handler: @escaping (Result) -> Void = { _ in }) -> SessionTaskType? { + open class func sendRequest(_ request: Req, callbackQueue: CallbackQueue? = nil, handler: @escaping (Result) -> Void = { _ in }) -> SessionTaskType? { return sharedSession.sendRequest(request, callbackQueue: callbackQueue, handler: handler) } /// Calls `cancelRequest(_:passingTest:)` of `sharedSession`. - open class func cancelRequest(_ requestType: Request.Type, passingTest test: @escaping (Request) -> Bool = { _ in true }) { + open class func cancelRequest(_ requestType: Req.Type, passingTest test: @escaping (Req) -> Bool = { _ in true }) { sharedSession.cancelRequest(requestType, passingTest: test) } /// Sends a request and receives the result as the argument of `handler` closure. This method takes - /// a type parameter `Request` that conforms to `RequestType` protocol. The result of passed request is + /// a type parameter `Request` that conforms to `Request` protocol. The result of passed request is /// expressed as `Result`. Since the response type /// `Request.Response` is inferred from `Request` type parameter, the it changes depending on the request type. /// - parameter request: The request to be sent. @@ -55,7 +55,7 @@ open class Session { /// - parameter handler: The closure that receives result of the request. /// - returns: The new session task. @discardableResult - open func sendRequest(_ request: Request, callbackQueue: CallbackQueue? = nil, handler: @escaping (Result) -> Void = { _ in }) -> SessionTaskType? { + open func sendRequest(_ request: Req, callbackQueue: CallbackQueue? = nil, handler: @escaping (Result) -> Void = { _ in }) -> SessionTaskType? { let callbackQueue = callbackQueue ?? self.callbackQueue let urlRequest: URLRequest @@ -69,7 +69,7 @@ open class Session { } let task = adapter.createTask(with: urlRequest) { data, urlResponse, error in - let result: Result + let result: Result switch (data, urlResponse, error) { case (_, _, let error?): @@ -100,11 +100,11 @@ open class Session { /// Cancels requests that passes the test. /// - parameter requestType: The request type to cancel. /// - parameter test: The test closure that determines if a request should be cancelled or not. - open func cancelRequest(_ requestType: Request.Type, passingTest test: @escaping (Request) -> Bool = { _ in true }) { + open func cancelRequest(_ requestType: Req.Type, passingTest test: @escaping (Req) -> Bool = { _ in true }) { adapter.getTasks { [weak self] tasks in return tasks .filter { task in - if let request = self?.requestForTask(task) as Request? { + if let request = self?.requestForTask(task) as Req? { return test(request) } else { return false @@ -114,11 +114,11 @@ open class Session { } } - private func setRequest(_ request: Request, forTask task: SessionTaskType) { + private func setRequest(_ request: Req, forTask task: SessionTaskType) { objc_setAssociatedObject(task, &taskRequestKey, request, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } - private func requestForTask(_ task: SessionTaskType) -> Request? { - return objc_getAssociatedObject(task, &taskRequestKey) as? Request + private func requestForTask(_ task: SessionTaskType) -> Req? { + return objc_getAssociatedObject(task, &taskRequestKey) as? Req } } diff --git a/Tests/APIKit/RequestTypeTests.swift b/Tests/APIKit/RequestTests.swift similarity index 99% rename from Tests/APIKit/RequestTypeTests.swift rename to Tests/APIKit/RequestTests.swift index c19d3ad0..617cb9e9 100644 --- a/Tests/APIKit/RequestTypeTests.swift +++ b/Tests/APIKit/RequestTests.swift @@ -1,7 +1,7 @@ import XCTest import APIKit -class RequestTypeTests: XCTestCase { +class RequestTests: XCTestCase { func testJapanesesQueryParameters() { let request = TestRequest(parameters: ["q": "こんにちは"]) let urlRequest = try? request.buildURLRequest() diff --git a/Tests/APIKit/SessionTests.swift b/Tests/APIKit/SessionTests.swift index 8cf92d68..5aa90e6a 100644 --- a/Tests/APIKit/SessionTests.swift +++ b/Tests/APIKit/SessionTests.swift @@ -176,7 +176,7 @@ class SessionTests: XCTestCase { waitForExpectations(timeout: 1.0, handler: nil) } - struct AnotherTestRequest: RequestType { + struct AnotherTestRequest: Request { typealias Response = Void var baseUrl: URL { @@ -196,7 +196,7 @@ class SessionTests: XCTestCase { } } - func testCancelOtherRequestType() { + func testCancelOtherRequest() { let successExpectation = expectation(description: "wait for response") let successRequest = AnotherTestRequest() @@ -239,12 +239,12 @@ class SessionTests: XCTestCase { return testSesssion } - private override func sendRequest(_ request: Request, callbackQueue: CallbackQueue?, handler: @escaping (Result) -> Void) -> SessionTaskType? { + private override func sendRequest(_ request: Req, callbackQueue: CallbackQueue?, handler: @escaping (Result) -> Void) -> SessionTaskType? { functionCallFlags[(#function)] = true return super.sendRequest(request) } - private override func cancelRequest(_ requestType: Request.Type, passingTest test: @escaping (Request) -> Bool) { + private override func cancelRequest(_ requestType: Req.Type, passingTest test: @escaping (Req) -> Bool) { functionCallFlags[(#function)] = true } } diff --git a/Tests/APIKit/TestComponents/TestRequest.swift b/Tests/APIKit/TestComponents/TestRequest.swift index 1ee4292e..bf6e6a58 100644 --- a/Tests/APIKit/TestComponents/TestRequest.swift +++ b/Tests/APIKit/TestComponents/TestRequest.swift @@ -1,13 +1,13 @@ import Foundation import APIKit -struct TestRequest: RequestType { +struct TestRequest: Request { var absoluteUrl: URL? { let urlRequest = try? buildURLRequest() return urlRequest?.url } - // MARK: RequestType + // MARK: Request typealias Response = Any init(baseUrl: String = "https://example.com", path: String = "/", method: HTTPMethod = .get, parameters: Any? = [:], headerFields: [String: String] = [:], interceptURLRequest: @escaping (URLRequest) throws -> URLRequest = { $0 }) { From 648311eacfd212914d26dbee2363b124ada28ca2 Mon Sep 17 00:00:00 2001 From: Syo Ikeda Date: Fri, 16 Sep 2016 14:14:36 +0900 Subject: [PATCH 32/38] Rename BodyParametersType to BodyParameters --- APIKit.xcodeproj/project.pbxproj | 14 +++++++------- .../AbstractInputStream.m | 0 .../BodyParameters.swift} | 4 ++-- .../Data+InputStream.swift | 0 .../FormURLEncodedBodyParameters.swift | 4 ++-- .../JSONBodyParameters.swift | 4 ++-- .../MultipartFormDataBodyParameters.swift | 4 ++-- Sources/Request.swift | 4 ++-- 8 files changed, 17 insertions(+), 17 deletions(-) rename Sources/{BodyParametersType => BodyParameters}/AbstractInputStream.m (100%) rename Sources/{BodyParametersType/BodyParametersType.swift => BodyParameters/BodyParameters.swift} (80%) rename Sources/{BodyParametersType => BodyParameters}/Data+InputStream.swift (100%) rename Sources/{BodyParametersType => BodyParameters}/FormURLEncodedBodyParameters.swift (91%) rename Sources/{BodyParametersType => BodyParameters}/JSONBodyParameters.swift (93%) rename Sources/{BodyParametersType => BodyParameters}/MultipartFormDataBodyParameters.swift (99%) diff --git a/APIKit.xcodeproj/project.pbxproj b/APIKit.xcodeproj/project.pbxproj index e8ce3d08..c15d7333 100644 --- a/APIKit.xcodeproj/project.pbxproj +++ b/APIKit.xcodeproj/project.pbxproj @@ -15,7 +15,7 @@ 7F09BF931C8AE8DB00F4A59A /* RequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7F09BF8D1C8AE8DB00F4A59A /* RequestTests.swift */; }; 7F10D8EE1CD5CF8D00722F66 /* CallbackQueue.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7F10D8ED1CD5CF8D00722F66 /* CallbackQueue.swift */; }; 7F10D8F01CD5D10100722F66 /* SessionCallbackQueueTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7F10D8EF1CD5D10100722F66 /* SessionCallbackQueueTests.swift */; }; - 7F18BD0F1C972C38003A31DF /* BodyParametersType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7F18BD0E1C972C38003A31DF /* BodyParametersType.swift */; }; + 7F18BD0F1C972C38003A31DF /* BodyParameters.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7F18BD0E1C972C38003A31DF /* BodyParameters.swift */; }; 7F18BD111C972C69003A31DF /* JSONBodyParameters.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7F18BD101C972C69003A31DF /* JSONBodyParameters.swift */; }; 7F18BD131C972E5A003A31DF /* FormURLEncodedBodyParameters.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7F18BD121C972E5A003A31DF /* FormURLEncodedBodyParameters.swift */; }; 7F18BD1A1C9730ED003A31DF /* URLEncodedSerialization.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7F18BD181C9730ED003A31DF /* URLEncodedSerialization.swift */; }; @@ -88,7 +88,7 @@ 7F09BF8D1C8AE8DB00F4A59A /* RequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RequestTests.swift; sourceTree = ""; }; 7F10D8ED1CD5CF8D00722F66 /* CallbackQueue.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CallbackQueue.swift; sourceTree = ""; }; 7F10D8EF1CD5D10100722F66 /* SessionCallbackQueueTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SessionCallbackQueueTests.swift; sourceTree = ""; }; - 7F18BD0E1C972C38003A31DF /* BodyParametersType.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = BodyParametersType.swift; sourceTree = ""; }; + 7F18BD0E1C972C38003A31DF /* BodyParameters.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = BodyParameters.swift; sourceTree = ""; }; 7F18BD101C972C69003A31DF /* JSONBodyParameters.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = JSONBodyParameters.swift; sourceTree = ""; }; 7F18BD121C972E5A003A31DF /* FormURLEncodedBodyParameters.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FormURLEncodedBodyParameters.swift; sourceTree = ""; }; 7F18BD181C9730ED003A31DF /* URLEncodedSerialization.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = URLEncodedSerialization.swift; sourceTree = ""; }; @@ -194,17 +194,17 @@ name = "Supporting Files"; sourceTree = ""; }; - 7F18BD0D1C972C38003A31DF /* BodyParametersType */ = { + 7F18BD0D1C972C38003A31DF /* BodyParameters */ = { isa = PBXGroup; children = ( - 7F18BD0E1C972C38003A31DF /* BodyParametersType.swift */, + 7F18BD0E1C972C38003A31DF /* BodyParameters.swift */, 7F18BD101C972C69003A31DF /* JSONBodyParameters.swift */, 7F18BD121C972E5A003A31DF /* FormURLEncodedBodyParameters.swift */, 7FA19A311C98542E005D25AE /* MultipartFormDataBodyParameters.swift */, 7F2A15BC1CEB5F67009A12A2 /* Data+InputStream.swift */, 7FAC64AC1CDC7ADE00F1BB45 /* AbstractInputStream.m */, ); - path = BodyParametersType; + path = BodyParameters; sourceTree = ""; }; 7F18BD161C9730ED003A31DF /* Serializations */ = { @@ -243,7 +243,7 @@ 7F7E8F0C1C8AD4B1008A13A9 /* HTTPMethod.swift */, 7F10D8ED1CD5CF8D00722F66 /* CallbackQueue.swift */, 7F85FB8B1C9D317300CEE132 /* SessionAdapterType */, - 7F18BD0D1C972C38003A31DF /* BodyParametersType */, + 7F18BD0D1C972C38003A31DF /* BodyParameters */, 7FA19A441C9CC9A2005D25AE /* DataParserType */, 7F18BD161C9730ED003A31DF /* Serializations */, 7FA19A3D1C9CBF2A005D25AE /* Error */, @@ -448,7 +448,7 @@ 7F85FB871C9CF47300CEE132 /* FormURLEncodedDataParser.swift in Sources */, 7FA19A431C9CBF2A005D25AE /* SessionTaskError.swift in Sources */, 7F7E8F1C1C8AD4B1008A13A9 /* Session.swift in Sources */, - 7F18BD0F1C972C38003A31DF /* BodyParametersType.swift in Sources */, + 7F18BD0F1C972C38003A31DF /* BodyParameters.swift in Sources */, 7F2A15BD1CEB5F67009A12A2 /* Data+InputStream.swift in Sources */, 7FB650DF1CEA0E6B00366992 /* StringDataParser.swift in Sources */, 7F18BD131C972E5A003A31DF /* FormURLEncodedBodyParameters.swift in Sources */, diff --git a/Sources/BodyParametersType/AbstractInputStream.m b/Sources/BodyParameters/AbstractInputStream.m similarity index 100% rename from Sources/BodyParametersType/AbstractInputStream.m rename to Sources/BodyParameters/AbstractInputStream.m diff --git a/Sources/BodyParametersType/BodyParametersType.swift b/Sources/BodyParameters/BodyParameters.swift similarity index 80% rename from Sources/BodyParametersType/BodyParametersType.swift rename to Sources/BodyParameters/BodyParameters.swift index 9b73aa0c..6670ca56 100644 --- a/Sources/BodyParametersType/BodyParametersType.swift +++ b/Sources/BodyParameters/BodyParameters.swift @@ -9,8 +9,8 @@ public enum RequestBodyEntity { case inputStream(InputStream) } -/// `BodyParametersType` provides interface to parse HTTP response body and to state `Content-Type` to accept. -public protocol BodyParametersType { +/// `BodyParameters` provides interface to parse HTTP response body and to state `Content-Type` to accept. +public protocol BodyParameters { /// `Content-Type` to send. The value for this property will be set to `Accept` HTTP header field. var contentType: String { get } diff --git a/Sources/BodyParametersType/Data+InputStream.swift b/Sources/BodyParameters/Data+InputStream.swift similarity index 100% rename from Sources/BodyParametersType/Data+InputStream.swift rename to Sources/BodyParameters/Data+InputStream.swift diff --git a/Sources/BodyParametersType/FormURLEncodedBodyParameters.swift b/Sources/BodyParameters/FormURLEncodedBodyParameters.swift similarity index 91% rename from Sources/BodyParametersType/FormURLEncodedBodyParameters.swift rename to Sources/BodyParameters/FormURLEncodedBodyParameters.swift index bba787ba..46c3ce5f 100644 --- a/Sources/BodyParametersType/FormURLEncodedBodyParameters.swift +++ b/Sources/BodyParameters/FormURLEncodedBodyParameters.swift @@ -1,7 +1,7 @@ import Foundation /// `FormURLEncodedBodyParameters` serializes form object for HTTP body and states its content type is form. -public struct FormURLEncodedBodyParameters: BodyParametersType { +public struct FormURLEncodedBodyParameters: BodyParameters { /// The form object to be serialized. public let form: [String: Any] @@ -14,7 +14,7 @@ public struct FormURLEncodedBodyParameters: BodyParametersType { self.encoding = encoding } - // MARK: - BodyParametersType + // MARK: - BodyParameters /// `Content-Type` to send. The value for this property will be set to `Accept` HTTP header field. public var contentType: String { diff --git a/Sources/BodyParametersType/JSONBodyParameters.swift b/Sources/BodyParameters/JSONBodyParameters.swift similarity index 93% rename from Sources/BodyParametersType/JSONBodyParameters.swift rename to Sources/BodyParameters/JSONBodyParameters.swift index 7a8eabf6..3f541917 100644 --- a/Sources/BodyParametersType/JSONBodyParameters.swift +++ b/Sources/BodyParameters/JSONBodyParameters.swift @@ -1,7 +1,7 @@ import Foundation /// `JSONBodyParameters` serializes JSON object for HTTP body and states its content type is JSON. -public struct JSONBodyParameters: BodyParametersType { +public struct JSONBodyParameters: BodyParameters { /// The JSON object to be serialized. public let JSONObject: Any @@ -14,7 +14,7 @@ public struct JSONBodyParameters: BodyParametersType { self.writingOptions = writingOptions } - // MARK: - BodyParametersType + // MARK: - BodyParameters /// `Content-Type` to send. The value for this property will be set to `Accept` HTTP header field. public var contentType: String { diff --git a/Sources/BodyParametersType/MultipartFormDataBodyParameters.swift b/Sources/BodyParameters/MultipartFormDataBodyParameters.swift similarity index 99% rename from Sources/BodyParametersType/MultipartFormDataBodyParameters.swift rename to Sources/BodyParameters/MultipartFormDataBodyParameters.swift index 999da390..e45c1282 100644 --- a/Sources/BodyParametersType/MultipartFormDataBodyParameters.swift +++ b/Sources/BodyParameters/MultipartFormDataBodyParameters.swift @@ -7,7 +7,7 @@ import Foundation #endif /// `FormURLEncodedBodyParameters` serializes array of `Part` for HTTP body and states its content type is multipart/form-data. -public struct MultipartFormDataBodyParameters: BodyParametersType { +public struct MultipartFormDataBodyParameters: BodyParameters { /// `EntityType` represents wheather the entity is expressed as `Data` or `InputStream`. public enum EntityType { /// Expresses the entity as `Data`, which has faster upload speed and lager memory usage. @@ -27,7 +27,7 @@ public struct MultipartFormDataBodyParameters: BodyParametersType { self.entityType = entityType } - // MARK: BodyParametersType + // MARK: BodyParameters /// `Content-Type` to send. The value for this property will be set to `Accept` HTTP header field. public var contentType: String { diff --git a/Sources/Request.swift b/Sources/Request.swift index 63408d1e..d68d6e61 100644 --- a/Sources/Request.swift +++ b/Sources/Request.swift @@ -33,7 +33,7 @@ public protocol Request { /// The actual parameters for the HTTP body. If this property is not implemented and `method.prefersQueryParameter` is `false`, /// the value of this property will be computed from `parameters` using `JSONBodyParameters`. - var bodyParameters: BodyParametersType? { get } + var bodyParameters: BodyParameters? { get } /// The HTTP header fields. In addition to fields defined in this property, `Accept` and `Content-Type` /// fields will be added by `dataParser` and `bodyParameters`. If you define `Accept` and `Content-Type` @@ -74,7 +74,7 @@ public extension Request { return parameters } - public var bodyParameters: BodyParametersType? { + public var bodyParameters: BodyParameters? { guard let parameters = parameters, !method.prefersQueryParameters else { return nil } From b0435a69a0af8e3d0c1784a366debac30050d6e5 Mon Sep 17 00:00:00 2001 From: Syo Ikeda Date: Fri, 16 Sep 2016 14:16:23 +0900 Subject: [PATCH 33/38] Rename DataParserType to DataParser --- APIKit.xcodeproj/project.pbxproj | 14 +++++++------- .../DataParser.swift} | 4 ++-- .../FormURLEncodedDataParser.swift | 4 ++-- .../JSONDataParser.swift | 4 ++-- .../StringDataParser.swift | 4 ++-- Sources/Request.swift | 4 ++-- 6 files changed, 17 insertions(+), 17 deletions(-) rename Sources/{DataParserType/DataParserType.swift => DataParser/DataParser.swift} (68%) rename Sources/{DataParserType => DataParser}/FormURLEncodedDataParser.swift (93%) rename Sources/{DataParserType => DataParser}/JSONDataParser.swift (92%) rename Sources/{DataParserType => DataParser}/StringDataParser.swift (91%) diff --git a/APIKit.xcodeproj/project.pbxproj b/APIKit.xcodeproj/project.pbxproj index c15d7333..d696b5ff 100644 --- a/APIKit.xcodeproj/project.pbxproj +++ b/APIKit.xcodeproj/project.pbxproj @@ -45,7 +45,7 @@ 7FA19A411C9CBF2A005D25AE /* RequestError.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7FA19A3E1C9CBF2A005D25AE /* RequestError.swift */; }; 7FA19A421C9CBF2A005D25AE /* ResponseError.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7FA19A3F1C9CBF2A005D25AE /* ResponseError.swift */; }; 7FA19A431C9CBF2A005D25AE /* SessionTaskError.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7FA19A401C9CBF2A005D25AE /* SessionTaskError.swift */; }; - 7FA19A461C9CC9D0005D25AE /* DataParserType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7FA19A451C9CC9D0005D25AE /* DataParserType.swift */; }; + 7FA19A461C9CC9D0005D25AE /* DataParser.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7FA19A451C9CC9D0005D25AE /* DataParser.swift */; }; 7FAC64AE1CDC7ADE00F1BB45 /* AbstractInputStream.m in Sources */ = {isa = PBXBuildFile; fileRef = 7FAC64AC1CDC7ADE00F1BB45 /* AbstractInputStream.m */; }; 7FB650DF1CEA0E6B00366992 /* StringDataParser.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7FB650DE1CEA0E6B00366992 /* StringDataParser.swift */; }; 7FB650E11CEA0F3D00366992 /* StringDataParserTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7FB650E01CEA0F3D00366992 /* StringDataParserTests.swift */; }; @@ -120,7 +120,7 @@ 7FA19A3E1C9CBF2A005D25AE /* RequestError.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RequestError.swift; sourceTree = ""; }; 7FA19A3F1C9CBF2A005D25AE /* ResponseError.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ResponseError.swift; sourceTree = ""; }; 7FA19A401C9CBF2A005D25AE /* SessionTaskError.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SessionTaskError.swift; sourceTree = ""; }; - 7FA19A451C9CC9D0005D25AE /* DataParserType.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DataParserType.swift; sourceTree = ""; }; + 7FA19A451C9CC9D0005D25AE /* DataParser.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DataParser.swift; sourceTree = ""; }; 7FAC64AC1CDC7ADE00F1BB45 /* AbstractInputStream.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AbstractInputStream.m; sourceTree = ""; }; 7FB650DE1CEA0E6B00366992 /* StringDataParser.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StringDataParser.swift; sourceTree = ""; }; 7FB650E01CEA0F3D00366992 /* StringDataParserTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StringDataParserTests.swift; sourceTree = ""; }; @@ -244,7 +244,7 @@ 7F10D8ED1CD5CF8D00722F66 /* CallbackQueue.swift */, 7F85FB8B1C9D317300CEE132 /* SessionAdapterType */, 7F18BD0D1C972C38003A31DF /* BodyParameters */, - 7FA19A441C9CC9A2005D25AE /* DataParserType */, + 7FA19A441C9CC9A2005D25AE /* DataParser */, 7F18BD161C9730ED003A31DF /* Serializations */, 7FA19A3D1C9CBF2A005D25AE /* Error */, 7F7E8F1E1C8AD4E6008A13A9 /* Supporting Files */, @@ -321,15 +321,15 @@ path = Error; sourceTree = ""; }; - 7FA19A441C9CC9A2005D25AE /* DataParserType */ = { + 7FA19A441C9CC9A2005D25AE /* DataParser */ = { isa = PBXGroup; children = ( - 7FA19A451C9CC9D0005D25AE /* DataParserType.swift */, + 7FA19A451C9CC9D0005D25AE /* DataParser.swift */, 7F85FB7F1C9CF12600CEE132 /* JSONDataParser.swift */, 7F85FB861C9CF47300CEE132 /* FormURLEncodedDataParser.swift */, 7FB650DE1CEA0E6B00366992 /* StringDataParser.swift */, ); - path = DataParserType; + path = DataParser; sourceTree = ""; }; /* End PBXGroup section */ @@ -452,7 +452,7 @@ 7F2A15BD1CEB5F67009A12A2 /* Data+InputStream.swift in Sources */, 7FB650DF1CEA0E6B00366992 /* StringDataParser.swift in Sources */, 7F18BD131C972E5A003A31DF /* FormURLEncodedBodyParameters.swift in Sources */, - 7FA19A461C9CC9D0005D25AE /* DataParserType.swift in Sources */, + 7FA19A461C9CC9D0005D25AE /* DataParser.swift in Sources */, 7F18BD111C972C69003A31DF /* JSONBodyParameters.swift in Sources */, 7F10D8EE1CD5CF8D00722F66 /* CallbackQueue.swift in Sources */, 7FA19A411C9CBF2A005D25AE /* RequestError.swift in Sources */, diff --git a/Sources/DataParserType/DataParserType.swift b/Sources/DataParser/DataParser.swift similarity index 68% rename from Sources/DataParserType/DataParserType.swift rename to Sources/DataParser/DataParser.swift index 8ec5bdea..1722bb51 100644 --- a/Sources/DataParserType/DataParserType.swift +++ b/Sources/DataParser/DataParser.swift @@ -1,7 +1,7 @@ import Foundation -/// `DataParserType` protocol provides inteface to parse HTTP response body and to state Content-Type to accept. -public protocol DataParserType { +/// `DataParser` protocol provides inteface to parse HTTP response body and to state Content-Type to accept. +public protocol DataParser { /// Value for `Accept` header field of HTTP request. var contentType: String? { get } diff --git a/Sources/DataParserType/FormURLEncodedDataParser.swift b/Sources/DataParser/FormURLEncodedDataParser.swift similarity index 93% rename from Sources/DataParserType/FormURLEncodedDataParser.swift rename to Sources/DataParser/FormURLEncodedDataParser.swift index 19f67d1d..fc46457e 100644 --- a/Sources/DataParserType/FormURLEncodedDataParser.swift +++ b/Sources/DataParser/FormURLEncodedDataParser.swift @@ -1,7 +1,7 @@ import Foundation /// `FormURLEncodedDataParser` parses form URL encoded response data. -public class FormURLEncodedDataParser: DataParserType { +public class FormURLEncodedDataParser: DataParser { public enum Error: Swift.Error { case cannotGetStringFromData(Data) } @@ -14,7 +14,7 @@ public class FormURLEncodedDataParser: DataParserType { self.encoding = encoding } - // MARK: - DataParserType + // MARK: - DataParser /// Value for `Accept` header field of HTTP request. public var contentType: String? { diff --git a/Sources/DataParserType/JSONDataParser.swift b/Sources/DataParser/JSONDataParser.swift similarity index 92% rename from Sources/DataParserType/JSONDataParser.swift rename to Sources/DataParser/JSONDataParser.swift index 3b44de54..0b28e98a 100644 --- a/Sources/DataParserType/JSONDataParser.swift +++ b/Sources/DataParser/JSONDataParser.swift @@ -1,7 +1,7 @@ import Foundation /// `JSONDataParser` response JSON data. -public class JSONDataParser: DataParserType { +public class JSONDataParser: DataParser { /// Options for reading the JSON data and creating the objects. public let readingOptions: JSONSerialization.ReadingOptions @@ -10,7 +10,7 @@ public class JSONDataParser: DataParserType { self.readingOptions = readingOptions } - // MARK: - DataParserType + // MARK: - DataParser /// Value for `Accept` header field of HTTP request. public var contentType: String? { diff --git a/Sources/DataParserType/StringDataParser.swift b/Sources/DataParser/StringDataParser.swift similarity index 91% rename from Sources/DataParserType/StringDataParser.swift rename to Sources/DataParser/StringDataParser.swift index 7ba9ac8b..6ae648f6 100644 --- a/Sources/DataParserType/StringDataParser.swift +++ b/Sources/DataParser/StringDataParser.swift @@ -1,7 +1,7 @@ import Foundation /// `StringDataParser` parses data and convert it to string. -public class StringDataParser: DataParserType { +public class StringDataParser: DataParser { public enum Error: Swift.Error { case invalidData(Data) } @@ -14,7 +14,7 @@ public class StringDataParser: DataParserType { self.encoding = encoding } - // MARK: - DataParserType + // MARK: - DataParser /// Value for `Accept` header field of HTTP request. public var contentType: String? { diff --git a/Sources/Request.swift b/Sources/Request.swift index d68d6e61..d578891a 100644 --- a/Sources/Request.swift +++ b/Sources/Request.swift @@ -41,7 +41,7 @@ public protocol Request { var headerFields: [String: String] { get } /// The parser object that states `Content-Type` to accept and parses response body. - var dataParser: DataParserType { get } + var dataParser: DataParser { get } /// Intercepts `URLRequest` which is created by `Request.buildURLRequest()`. If an error is /// thrown in this method, the result of `Session.sendRequest()` turns `.failure(.requestError(error))`. @@ -86,7 +86,7 @@ public extension Request { return [:] } - public var dataParser: DataParserType { + public var dataParser: DataParser { return JSONDataParser(readingOptions: []) } From df1df608b76ee05f663c42c26705fb22eeb64d01 Mon Sep 17 00:00:00 2001 From: Syo Ikeda Date: Fri, 16 Sep 2016 14:18:54 +0900 Subject: [PATCH 34/38] Rename SessionAdapterType to SessionAdapter --- APIKit.xcodeproj/project.pbxproj | 14 +++++++------- Sources/Session.swift | 4 ++-- .../SessionAdapter.swift} | 6 +++--- .../URLSessionAdapter.swift | 2 +- .../APIKit/TestComponents/TestSessionAdapter.swift | 2 +- 5 files changed, 14 insertions(+), 14 deletions(-) rename Sources/{SessionAdapterType/SessionAdapterType.swift => SessionAdapter/SessionAdapter.swift} (77%) rename Sources/{SessionAdapterType => SessionAdapter}/URLSessionAdapter.swift (96%) diff --git a/APIKit.xcodeproj/project.pbxproj b/APIKit.xcodeproj/project.pbxproj index d696b5ff..266111fd 100644 --- a/APIKit.xcodeproj/project.pbxproj +++ b/APIKit.xcodeproj/project.pbxproj @@ -32,7 +32,7 @@ 7F85FB871C9CF47300CEE132 /* FormURLEncodedDataParser.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7F85FB861C9CF47300CEE132 /* FormURLEncodedDataParser.swift */; }; 7F85FB891C9CF7B000CEE132 /* FormURLEncodedDataParserTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7F85FB881C9CF7B000CEE132 /* FormURLEncodedDataParserTests.swift */; }; 7F85FB8E1C9D317300CEE132 /* URLSessionAdapter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7F85FB8C1C9D317300CEE132 /* URLSessionAdapter.swift */; }; - 7F85FB8F1C9D317300CEE132 /* SessionAdapterType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7F85FB8D1C9D317300CEE132 /* SessionAdapterType.swift */; }; + 7F85FB8F1C9D317300CEE132 /* SessionAdapter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7F85FB8D1C9D317300CEE132 /* SessionAdapter.swift */; }; 7F85FB921C9D336D00CEE132 /* URLSessionAdapterTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7F85FB911C9D336D00CEE132 /* URLSessionAdapterTests.swift */; }; 7F85FB9A1C9D3DA700CEE132 /* TestRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7F85FB981C9D3DA700CEE132 /* TestRequest.swift */; }; 7F85FB9B1C9D3DA700CEE132 /* TestSessionAdapter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7F85FB991C9D3DA700CEE132 /* TestSessionAdapter.swift */; }; @@ -106,7 +106,7 @@ 7F85FB861C9CF47300CEE132 /* FormURLEncodedDataParser.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FormURLEncodedDataParser.swift; sourceTree = ""; }; 7F85FB881C9CF7B000CEE132 /* FormURLEncodedDataParserTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FormURLEncodedDataParserTests.swift; sourceTree = ""; }; 7F85FB8C1C9D317300CEE132 /* URLSessionAdapter.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = URLSessionAdapter.swift; sourceTree = ""; }; - 7F85FB8D1C9D317300CEE132 /* SessionAdapterType.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SessionAdapterType.swift; sourceTree = ""; }; + 7F85FB8D1C9D317300CEE132 /* SessionAdapter.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SessionAdapter.swift; sourceTree = ""; }; 7F85FB911C9D336D00CEE132 /* URLSessionAdapterTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = URLSessionAdapterTests.swift; sourceTree = ""; }; 7F85FB981C9D3DA700CEE132 /* TestRequest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TestRequest.swift; sourceTree = ""; }; 7F85FB991C9D3DA700CEE132 /* TestSessionAdapter.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TestSessionAdapter.swift; sourceTree = ""; }; @@ -242,7 +242,7 @@ 7F7E8F101C8AD4B1008A13A9 /* Request.swift */, 7F7E8F0C1C8AD4B1008A13A9 /* HTTPMethod.swift */, 7F10D8ED1CD5CF8D00722F66 /* CallbackQueue.swift */, - 7F85FB8B1C9D317300CEE132 /* SessionAdapterType */, + 7F85FB8B1C9D317300CEE132 /* SessionAdapter */, 7F18BD0D1C972C38003A31DF /* BodyParameters */, 7FA19A441C9CC9A2005D25AE /* DataParser */, 7F18BD161C9730ED003A31DF /* Serializations */, @@ -272,13 +272,13 @@ path = DataParserType; sourceTree = ""; }; - 7F85FB8B1C9D317300CEE132 /* SessionAdapterType */ = { + 7F85FB8B1C9D317300CEE132 /* SessionAdapter */ = { isa = PBXGroup; children = ( - 7F85FB8D1C9D317300CEE132 /* SessionAdapterType.swift */, + 7F85FB8D1C9D317300CEE132 /* SessionAdapter.swift */, 7F85FB8C1C9D317300CEE132 /* URLSessionAdapter.swift */, ); - path = SessionAdapterType; + path = SessionAdapter; sourceTree = ""; }; 7F85FB901C9D335F00CEE132 /* SessionAdapterType */ = { @@ -456,7 +456,7 @@ 7F18BD111C972C69003A31DF /* JSONBodyParameters.swift in Sources */, 7F10D8EE1CD5CF8D00722F66 /* CallbackQueue.swift in Sources */, 7FA19A411C9CBF2A005D25AE /* RequestError.swift in Sources */, - 7F85FB8F1C9D317300CEE132 /* SessionAdapterType.swift in Sources */, + 7F85FB8F1C9D317300CEE132 /* SessionAdapter.swift in Sources */, 7F85FB801C9CF12600CEE132 /* JSONDataParser.swift in Sources */, 7F18BD1A1C9730ED003A31DF /* URLEncodedSerialization.swift in Sources */, 7FAC64AE1CDC7ADE00F1BB45 /* AbstractInputStream.m in Sources */, diff --git a/Sources/Session.swift b/Sources/Session.swift index 8f7f81fe..84556316 100644 --- a/Sources/Session.swift +++ b/Sources/Session.swift @@ -6,7 +6,7 @@ private var taskRequestKey = 0 /// `Session` manages tasks for HTTP/HTTPS requests. open class Session { /// The adapter that connects `Session` instance and lower level backend. - public let adapter: SessionAdapterType + public let adapter: SessionAdapter /// The default callback queue for `sendRequest(_:handler:)`. public let callbackQueue: CallbackQueue @@ -14,7 +14,7 @@ open class Session { /// Returns `Session` instance that is initialized with `adapter`. /// - parameter adapter: The adapter that connects lower level backend with Session interface. /// - parameter callbackQueue: The default callback queue for `sendRequest(_:handler:)`. - public init(adapter: SessionAdapterType, callbackQueue: CallbackQueue = .main) { + public init(adapter: SessionAdapter, callbackQueue: CallbackQueue = .main) { self.adapter = adapter self.callbackQueue = callbackQueue } diff --git a/Sources/SessionAdapterType/SessionAdapterType.swift b/Sources/SessionAdapter/SessionAdapter.swift similarity index 77% rename from Sources/SessionAdapterType/SessionAdapterType.swift rename to Sources/SessionAdapter/SessionAdapter.swift index 368a9555..df9cdc85 100644 --- a/Sources/SessionAdapterType/SessionAdapterType.swift +++ b/Sources/SessionAdapter/SessionAdapter.swift @@ -6,10 +6,10 @@ public protocol SessionTaskType: class { func cancel() } -/// `SessionAdapterType` protocol provides interface to connect lower level networking backend with `Session`. -/// APIKit provides `URLSessionAdapter`, which conforms to `SessionAdapterType`, to connect `URLSession` +/// `SessionAdapter` protocol provides interface to connect lower level networking backend with `Session`. +/// APIKit provides `URLSessionAdapter`, which conforms to `SessionAdapter`, to connect `URLSession` /// with `Session`. -public protocol SessionAdapterType { +public protocol SessionAdapter { /// Returns instance that conforms to `SessionTaskType`. `handler` must be called after success or failure. func createTask(with URLRequest: URLRequest, handler: @escaping (Data?, URLResponse?, Error?) -> Void) -> SessionTaskType diff --git a/Sources/SessionAdapterType/URLSessionAdapter.swift b/Sources/SessionAdapter/URLSessionAdapter.swift similarity index 96% rename from Sources/SessionAdapterType/URLSessionAdapter.swift rename to Sources/SessionAdapter/URLSessionAdapter.swift index 3abc3a98..edcc610b 100644 --- a/Sources/SessionAdapterType/URLSessionAdapter.swift +++ b/Sources/SessionAdapter/URLSessionAdapter.swift @@ -14,7 +14,7 @@ private var taskAssociatedObjectCompletionHandlerKey = 0 /// delegate methods that you want to implement. Since `URLSessionAdapter` also implements delegate methods /// `URLSession(_:task: didCompleteWithError:)` and `URLSession(_:dataTask:didReceiveData:)`, you have to call /// `super` in these methods if you implement them. -open class URLSessionAdapter: NSObject, SessionAdapterType, URLSessionDelegate, URLSessionTaskDelegate, URLSessionDataDelegate { +open class URLSessionAdapter: NSObject, SessionAdapter, URLSessionDelegate, URLSessionTaskDelegate, URLSessionDataDelegate { /// The undelying `URLSession` instance. open var urlSession: URLSession! diff --git a/Tests/APIKit/TestComponents/TestSessionAdapter.swift b/Tests/APIKit/TestComponents/TestSessionAdapter.swift index 52da166f..171996c2 100644 --- a/Tests/APIKit/TestComponents/TestSessionAdapter.swift +++ b/Tests/APIKit/TestComponents/TestSessionAdapter.swift @@ -1,7 +1,7 @@ import Foundation import APIKit -class TestSessionAdapter: SessionAdapterType { +class TestSessionAdapter: SessionAdapter { enum Error: Swift.Error { case cancelled } From 6cd44c7f1d0d5db93f203a84136cc1794acdcd43 Mon Sep 17 00:00:00 2001 From: Syo Ikeda Date: Fri, 16 Sep 2016 14:22:48 +0900 Subject: [PATCH 35/38] [Session] Rename `sendRequest` to `send` --- Demo.playground/Contents.swift | 2 +- Sources/CallbackQueue.swift | 2 +- Sources/Request.swift | 4 +-- Sources/Session.swift | 14 +++++----- .../URLSessionAdapterSubclassTests.swift | 2 +- .../URLSessionAdapterTests.swift | 6 ++-- Tests/APIKit/SessionCallbackQueueTests.swift | 12 ++++---- Tests/APIKit/SessionTests.swift | 28 +++++++++---------- 8 files changed, 35 insertions(+), 35 deletions(-) diff --git a/Demo.playground/Contents.swift b/Demo.playground/Contents.swift index ef869984..58700046 100644 --- a/Demo.playground/Contents.swift +++ b/Demo.playground/Contents.swift @@ -60,7 +60,7 @@ struct GetRateLimitRequest: GitHubRequest { //: Step 4: Send request let request = GetRateLimitRequest() -Session.sendRequest(request) { result in +Session.send(request) { result in switch result { case .success(let rateLimit): print("count: \(rateLimit.count)") diff --git a/Sources/CallbackQueue.swift b/Sources/CallbackQueue.swift index b689170c..6611eb8d 100644 --- a/Sources/CallbackQueue.swift +++ b/Sources/CallbackQueue.swift @@ -1,6 +1,6 @@ import Foundation -/// `CallbackQueue` represents queue where `handler` of `Session.sendRequest(_:handler:)` runs. +/// `CallbackQueue` represents queue where `handler` of `Session.send(_:handler:)` runs. public enum CallbackQueue { /// Dispatches callback closure on main queue asynchronously. case main diff --git a/Sources/Request.swift b/Sources/Request.swift index d578891a..49f9c941 100644 --- a/Sources/Request.swift +++ b/Sources/Request.swift @@ -44,12 +44,12 @@ public protocol Request { var dataParser: DataParser { get } /// Intercepts `URLRequest` which is created by `Request.buildURLRequest()`. If an error is - /// thrown in this method, the result of `Session.sendRequest()` turns `.failure(.requestError(error))`. + /// thrown in this method, the result of `Session.send()` turns `.failure(.requestError(error))`. /// - Throws: `ErrorType` func intercept(urlRequest: URLRequest) throws -> URLRequest /// Intercepts response `Any` and `HTTPURLResponse`. If an error is thrown in this method, - /// the result of `Session.sendRequest()` turns `.failure(.responseError(error))`. + /// the result of `Session.send()` turns `.failure(.responseError(error))`. /// The default implementation of this method is provided to throw `RequestError.unacceptableStatusCode` /// if the HTTP status code is not in `200..<300`. /// - Throws: `ErrorType` diff --git a/Sources/Session.swift b/Sources/Session.swift index 84556316..70fbcea4 100644 --- a/Sources/Session.swift +++ b/Sources/Session.swift @@ -8,12 +8,12 @@ open class Session { /// The adapter that connects `Session` instance and lower level backend. public let adapter: SessionAdapter - /// The default callback queue for `sendRequest(_:handler:)`. + /// The default callback queue for `send(_:handler:)`. public let callbackQueue: CallbackQueue /// Returns `Session` instance that is initialized with `adapter`. /// - parameter adapter: The adapter that connects lower level backend with Session interface. - /// - parameter callbackQueue: The default callback queue for `sendRequest(_:handler:)`. + /// - parameter callbackQueue: The default callback queue for `send(_:handler:)`. public init(adapter: SessionAdapter, callbackQueue: CallbackQueue = .main) { self.adapter = adapter self.callbackQueue = callbackQueue @@ -26,19 +26,19 @@ open class Session { return Session(adapter: adapter) }() - /// The shared `Session` instance for class methods, `Session.sendRequest(_:handler:)` and `Session.cancelRequest(_:passingTest:)`. + /// The shared `Session` instance for class methods, `Session.send(_:handler:)` and `Session.cancelRequest(_:passingTest:)`. open class var sharedSession: Session { return privateSharedSession } - /// Calls `sendRequest(_:handler:)` of `sharedSession`. + /// Calls `send(_:handler:)` of `sharedSession`. /// - parameter request: The request to be sent. /// - parameter callbackQueue: The queue where the handler runs. If this parameters is `nil`, default `callbackQueue` of `Session` will be used. /// - parameter handler: The closure that receives result of the request. /// - returns: The new session task. @discardableResult - open class func sendRequest(_ request: Req, callbackQueue: CallbackQueue? = nil, handler: @escaping (Result) -> Void = { _ in }) -> SessionTaskType? { - return sharedSession.sendRequest(request, callbackQueue: callbackQueue, handler: handler) + open class func send(_ request: Req, callbackQueue: CallbackQueue? = nil, handler: @escaping (Result) -> Void = { _ in }) -> SessionTaskType? { + return sharedSession.send(request, callbackQueue: callbackQueue, handler: handler) } /// Calls `cancelRequest(_:passingTest:)` of `sharedSession`. @@ -55,7 +55,7 @@ open class Session { /// - parameter handler: The closure that receives result of the request. /// - returns: The new session task. @discardableResult - open func sendRequest(_ request: Req, callbackQueue: CallbackQueue? = nil, handler: @escaping (Result) -> Void = { _ in }) -> SessionTaskType? { + open func send(_ request: Req, callbackQueue: CallbackQueue? = nil, handler: @escaping (Result) -> Void = { _ in }) -> SessionTaskType? { let callbackQueue = callbackQueue ?? self.callbackQueue let urlRequest: URLRequest diff --git a/Tests/APIKit/SessionAdapterType/URLSessionAdapterSubclassTests.swift b/Tests/APIKit/SessionAdapterType/URLSessionAdapterSubclassTests.swift index f6baa1ed..60c8f2e1 100644 --- a/Tests/APIKit/SessionAdapterType/URLSessionAdapterSubclassTests.swift +++ b/Tests/APIKit/SessionAdapterType/URLSessionAdapterSubclassTests.swift @@ -46,7 +46,7 @@ class URLSessionAdapterSubclassTests: XCTestCase { let expectation = self.expectation(description: "wait for response") let request = TestRequest() - session.sendRequest(request) { result in + session.send(request) { result in if case .failure = result { XCTFail() } diff --git a/Tests/APIKit/SessionAdapterType/URLSessionAdapterTests.swift b/Tests/APIKit/SessionAdapterType/URLSessionAdapterTests.swift index 43f1ab74..d76c754f 100644 --- a/Tests/APIKit/SessionAdapterType/URLSessionAdapterTests.swift +++ b/Tests/APIKit/SessionAdapterType/URLSessionAdapterTests.swift @@ -33,7 +33,7 @@ class URLSessionAdapterTests: XCTestCase { let expectation = self.expectation(description: "wait for response") let request = TestRequest() - session.sendRequest(request) { response in + session.send(request) { response in switch response { case .success(let dictionary): XCTAssertEqual((dictionary as? [String: String])?["key"], "value") @@ -60,7 +60,7 @@ class URLSessionAdapterTests: XCTestCase { let expectation = self.expectation(description: "wait for response") let request = TestRequest() - session.sendRequest(request) { response in + session.send(request) { response in switch response { case .success: XCTFail() @@ -93,7 +93,7 @@ class URLSessionAdapterTests: XCTestCase { let expectation = self.expectation(description: "wait for response") let request = TestRequest() - session.sendRequest(request) { result in + session.send(request) { result in guard case .failure(let error) = result, case .connectionError(let connectionError as NSError) = error else { XCTFail() diff --git a/Tests/APIKit/SessionCallbackQueueTests.swift b/Tests/APIKit/SessionCallbackQueueTests.swift index 8b309519..fa300e1f 100644 --- a/Tests/APIKit/SessionCallbackQueueTests.swift +++ b/Tests/APIKit/SessionCallbackQueueTests.swift @@ -20,7 +20,7 @@ class SessionCallbackQueueTests: XCTestCase { let expectation = self.expectation(description: "wait for response") let request = TestRequest() - session.sendRequest(request, callbackQueue: .main) { result in + session.send(request, callbackQueue: .main) { result in XCTAssert(Thread.isMainThread) expectation.fulfill() } @@ -32,7 +32,7 @@ class SessionCallbackQueueTests: XCTestCase { let expectation = self.expectation(description: "wait for response") let request = TestRequest() - session.sendRequest(request, callbackQueue: .sessionQueue) { result in + session.send(request, callbackQueue: .sessionQueue) { result in // This depends on implementation of TestSessionAdapter XCTAssert(Thread.isMainThread) expectation.fulfill() @@ -46,7 +46,7 @@ class SessionCallbackQueueTests: XCTestCase { let expectation = self.expectation(description: "wait for response") let request = TestRequest() - session.sendRequest(request, callbackQueue: .operationQueue(operationQueue)) { result in + session.send(request, callbackQueue: .operationQueue(operationQueue)) { result in XCTAssertEqual(OperationQueue.current, operationQueue) expectation.fulfill() } @@ -59,7 +59,7 @@ class SessionCallbackQueueTests: XCTestCase { let expectation = self.expectation(description: "wait for response") let request = TestRequest() - session.sendRequest(request, callbackQueue: .dispatchQueue(dispatchQueue)) { result in + session.send(request, callbackQueue: .dispatchQueue(dispatchQueue)) { result in // There is no way to test current dispatch queue. XCTAssert(!Thread.isMainThread) expectation.fulfill() @@ -76,7 +76,7 @@ class SessionCallbackQueueTests: XCTestCase { let expectation = self.expectation(description: "wait for response") let request = TestRequest() - session.sendRequest(request) { result in + session.send(request) { result in XCTAssertEqual(OperationQueue.current, operationQueue) expectation.fulfill() } @@ -91,7 +91,7 @@ class SessionCallbackQueueTests: XCTestCase { let expectation = self.expectation(description: "wait for response") let request = TestRequest() - session.sendRequest(request, callbackQueue: nil) { result in + session.send(request, callbackQueue: nil) { result in XCTAssertEqual(OperationQueue.current, operationQueue) expectation.fulfill() } diff --git a/Tests/APIKit/SessionTests.swift b/Tests/APIKit/SessionTests.swift index 5aa90e6a..8a07e1ea 100644 --- a/Tests/APIKit/SessionTests.swift +++ b/Tests/APIKit/SessionTests.swift @@ -22,7 +22,7 @@ class SessionTests: XCTestCase { let expectation = self.expectation(description: "wait for response") let request = TestRequest() - session.sendRequest(request) { response in + session.send(request) { response in switch response { case .success(let dictionary): XCTAssertEqual((dictionary as? [String: String])?["key"], "value") @@ -44,7 +44,7 @@ class SessionTests: XCTestCase { let expectation = self.expectation(description: "wait for response") let request = TestRequest() - session.sendRequest(request) { result in + session.send(request) { result in if case .failure(let error) = result, case .responseError(let responseError as NSError) = error { XCTAssertEqual(responseError.domain, NSCocoaErrorDomain) @@ -65,7 +65,7 @@ class SessionTests: XCTestCase { let expectation = self.expectation(description: "wait for response") let request = TestRequest() - session.sendRequest(request) { result in + session.send(request) { result in if case .failure(let error) = result, case .responseError(let responseError as ResponseError) = error, case .unacceptableStatusCode(let statusCode) = responseError { @@ -86,7 +86,7 @@ class SessionTests: XCTestCase { let expectation = self.expectation(description: "wait for response") let request = TestRequest() - session.sendRequest(request) { result in + session.send(request) { result in if case .failure(let error) = result, case .responseError(let responseError as ResponseError) = error, case .nonHTTPURLResponse(let urlResponse) = responseError { @@ -110,7 +110,7 @@ class SessionTests: XCTestCase { throw Error() } - session.sendRequest(request) { result in + session.send(request) { result in if case .failure(let error) = result, case .requestError(let requestError) = error { XCTAssert(requestError is Error) @@ -130,7 +130,7 @@ class SessionTests: XCTestCase { let expectation = self.expectation(description: "wait for response") let request = TestRequest() - session.sendRequest(request) { result in + session.send(request) { result in if case .failure(let error) = result, case .connectionError(let connectionError as NSError) = error { XCTAssertEqual(connectionError.code, 0) @@ -150,7 +150,7 @@ class SessionTests: XCTestCase { let successExpectation = expectation(description: "wait for response") let successRequest = TestRequest(path: "/success") - session.sendRequest(successRequest) { result in + session.send(successRequest) { result in if case .failure = result { XCTFail() } @@ -161,7 +161,7 @@ class SessionTests: XCTestCase { let failureExpectation = expectation(description: "wait for response") let failureRequest = TestRequest(path: "/failure") - session.sendRequest(failureRequest) { result in + session.send(failureRequest) { result in if case .success = result { XCTFail() } @@ -200,7 +200,7 @@ class SessionTests: XCTestCase { let successExpectation = expectation(description: "wait for response") let successRequest = AnotherTestRequest() - session.sendRequest(successRequest) { result in + session.send(successRequest) { result in if case .failure = result { XCTFail() } @@ -211,7 +211,7 @@ class SessionTests: XCTestCase { let failureExpectation = expectation(description: "wait for response") let failureRequest = TestRequest() - session.sendRequest(failureRequest) { result in + session.send(failureRequest) { result in if case .success = result { XCTFail() } @@ -239,9 +239,9 @@ class SessionTests: XCTestCase { return testSesssion } - private override func sendRequest(_ request: Req, callbackQueue: CallbackQueue?, handler: @escaping (Result) -> Void) -> SessionTaskType? { + private override func send(_ request: Req, callbackQueue: CallbackQueue?, handler: @escaping (Result) -> Void) -> SessionTaskType? { functionCallFlags[(#function)] = true - return super.sendRequest(request) + return super.send(request) } private override func cancelRequest(_ requestType: Req.Type, passingTest test: @escaping (Req) -> Bool) { @@ -250,10 +250,10 @@ class SessionTests: XCTestCase { } let testSession = SessionSubclass.testSesssion - SessionSubclass.sendRequest(TestRequest()) + SessionSubclass.send(TestRequest()) SessionSubclass.cancelRequest(TestRequest.self) - XCTAssertEqual(testSession.functionCallFlags["sendRequest(_:callbackQueue:handler:)"], true) + XCTAssertEqual(testSession.functionCallFlags["send(_:callbackQueue:handler:)"], true) XCTAssertEqual(testSession.functionCallFlags["cancelRequest(_:passingTest:)"], true) } } From e19c43d85baa933e3d654a022d73205f078478da Mon Sep 17 00:00:00 2001 From: Syo Ikeda Date: Fri, 16 Sep 2016 14:27:40 +0900 Subject: [PATCH 36/38] [Session] Rename `cancelRequest(_:passingTest:)` to `cancelRequests(withType:passingTest:)` --- Sources/Session.swift | 10 +++++----- .../SessionAdapterType/URLSessionAdapterTests.swift | 2 +- Tests/APIKit/SessionTests.swift | 12 ++++++------ 3 files changed, 12 insertions(+), 12 deletions(-) diff --git a/Sources/Session.swift b/Sources/Session.swift index 70fbcea4..b557652c 100644 --- a/Sources/Session.swift +++ b/Sources/Session.swift @@ -26,7 +26,7 @@ open class Session { return Session(adapter: adapter) }() - /// The shared `Session` instance for class methods, `Session.send(_:handler:)` and `Session.cancelRequest(_:passingTest:)`. + /// The shared `Session` instance for class methods, `Session.send(_:handler:)` and `Session.cancelRequests(withType:passingTest:)`. open class var sharedSession: Session { return privateSharedSession } @@ -41,9 +41,9 @@ open class Session { return sharedSession.send(request, callbackQueue: callbackQueue, handler: handler) } - /// Calls `cancelRequest(_:passingTest:)` of `sharedSession`. - open class func cancelRequest(_ requestType: Req.Type, passingTest test: @escaping (Req) -> Bool = { _ in true }) { - sharedSession.cancelRequest(requestType, passingTest: test) + /// Calls `cancelRequests(withType:passingTest:)` of `sharedSession`. + open class func cancelRequests(withType requestType: Req.Type, passingTest test: @escaping (Req) -> Bool = { _ in true }) { + sharedSession.cancelRequests(withType: requestType, passingTest: test) } /// Sends a request and receives the result as the argument of `handler` closure. This method takes @@ -100,7 +100,7 @@ open class Session { /// Cancels requests that passes the test. /// - parameter requestType: The request type to cancel. /// - parameter test: The test closure that determines if a request should be cancelled or not. - open func cancelRequest(_ requestType: Req.Type, passingTest test: @escaping (Req) -> Bool = { _ in true }) { + open func cancelRequests(withType requestType: Req.Type, passingTest test: @escaping (Req) -> Bool = { _ in true }) { adapter.getTasks { [weak self] tasks in return tasks .filter { task in diff --git a/Tests/APIKit/SessionAdapterType/URLSessionAdapterTests.swift b/Tests/APIKit/SessionAdapterType/URLSessionAdapterTests.swift index d76c754f..ba5ba38a 100644 --- a/Tests/APIKit/SessionAdapterType/URLSessionAdapterTests.swift +++ b/Tests/APIKit/SessionAdapterType/URLSessionAdapterTests.swift @@ -106,7 +106,7 @@ class URLSessionAdapterTests: XCTestCase { } DispatchQueue.main.async { - self.session.cancelRequest(TestRequest.self) + self.session.cancelRequests(withType: TestRequest.self) } waitForExpectations(timeout: 10.0, handler: nil) diff --git a/Tests/APIKit/SessionTests.swift b/Tests/APIKit/SessionTests.swift index 8a07e1ea..4a45c915 100644 --- a/Tests/APIKit/SessionTests.swift +++ b/Tests/APIKit/SessionTests.swift @@ -141,7 +141,7 @@ class SessionTests: XCTestCase { expectation.fulfill() } - session.cancelRequest(TestRequest.self) + session.cancelRequests(withType: TestRequest.self) waitForExpectations(timeout: 1.0, handler: nil) } @@ -169,7 +169,7 @@ class SessionTests: XCTestCase { failureExpectation.fulfill() } - session.cancelRequest(TestRequest.self) { request in + session.cancelRequests(withType: TestRequest.self) { request in return request.path == failureRequest.path } @@ -219,7 +219,7 @@ class SessionTests: XCTestCase { failureExpectation.fulfill() } - session.cancelRequest(TestRequest.self) + session.cancelRequests(withType: TestRequest.self) waitForExpectations(timeout: 1.0, handler: nil) } @@ -244,16 +244,16 @@ class SessionTests: XCTestCase { return super.send(request) } - private override func cancelRequest(_ requestType: Req.Type, passingTest test: @escaping (Req) -> Bool) { + private override func cancelRequests(withType requestType: Req.Type, passingTest test: @escaping (Req) -> Bool) { functionCallFlags[(#function)] = true } } let testSession = SessionSubclass.testSesssion SessionSubclass.send(TestRequest()) - SessionSubclass.cancelRequest(TestRequest.self) + SessionSubclass.cancelRequests(withType: TestRequest.self) XCTAssertEqual(testSession.functionCallFlags["send(_:callbackQueue:handler:)"], true) - XCTAssertEqual(testSession.functionCallFlags["cancelRequest(_:passingTest:)"], true) + XCTAssertEqual(testSession.functionCallFlags["cancelRequests(withType:passingTest:)"], true) } } From 41d3477b7459885d30ebfa2f15dacf97089b35d7 Mon Sep 17 00:00:00 2001 From: Syo Ikeda Date: Fri, 16 Sep 2016 14:48:56 +0900 Subject: [PATCH 37/38] URL should be named as `url` or `URL` --- Demo.playground/Contents.swift | 2 +- .../MultipartFormDataBodyParameters.swift | 14 +- Sources/Error/RequestError.swift | 2 +- Sources/Request.swift | 8 +- .../MultipartFormDataParametersTests.swift | 6 +- Tests/APIKit/RequestTests.swift | 148 +++++++++--------- Tests/APIKit/SessionTests.swift | 2 +- Tests/APIKit/TestComponents/TestRequest.swift | 8 +- 8 files changed, 95 insertions(+), 95 deletions(-) diff --git a/Demo.playground/Contents.swift b/Demo.playground/Contents.swift index 58700046..6bc8ac9b 100644 --- a/Demo.playground/Contents.swift +++ b/Demo.playground/Contents.swift @@ -10,7 +10,7 @@ protocol GitHubRequest: Request { } extension GitHubRequest { - var baseUrl: URL { + var baseURL: URL { return URL(string: "https://api.github.com")! } } diff --git a/Sources/BodyParameters/MultipartFormDataBodyParameters.swift b/Sources/BodyParameters/MultipartFormDataBodyParameters.swift index e45c1282..fe671246 100644 --- a/Sources/BodyParameters/MultipartFormDataBodyParameters.swift +++ b/Sources/BodyParameters/MultipartFormDataBodyParameters.swift @@ -90,20 +90,20 @@ public extension MultipartFormDataBodyParameters { /// Returns Part instance that has input stream of specifed file URL. /// If `mimeType` or `fileName` are `nil`, values for the fields will be detected from URL. - public init(fileUrl: URL, name: String, mimeType: String? = nil, fileName: String? = nil) throws { - guard let inputStream = InputStream(url: fileUrl) else { - throw Error.illegalFileURL(fileUrl) + public init(fileURL: URL, name: String, mimeType: String? = nil, fileName: String? = nil) throws { + guard let inputStream = InputStream(url: fileURL) else { + throw Error.illegalFileURL(fileURL) } - let fileSize = (try? FileManager.default.attributesOfItem(atPath: fileUrl.path)) + let fileSize = (try? FileManager.default.attributesOfItem(atPath: fileURL.path)) .flatMap { $0[FileAttributeKey.size] as? NSNumber } .map { $0.intValue } guard let bodyLength = fileSize else { - throw Error.cannotGetFileSize(fileUrl) + throw Error.cannotGetFileSize(fileURL) } - let detectedMimeType = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, fileUrl.pathExtension as CFString, nil) + let detectedMimeType = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, fileURL.pathExtension as CFString, nil) .map { $0.takeRetainedValue() } .flatMap { UTTypeCopyPreferredTagWithClass($0, kUTTagClassMIMEType)?.takeRetainedValue() } .map { $0 as String } @@ -111,7 +111,7 @@ public extension MultipartFormDataBodyParameters { self.inputStream = inputStream self.name = name self.mimeType = mimeType ?? detectedMimeType ?? "application/octet-stream" - self.fileName = fileName ?? fileUrl.lastPathComponent + self.fileName = fileName ?? fileURL.lastPathComponent self.count = bodyLength } } diff --git a/Sources/Error/RequestError.swift b/Sources/Error/RequestError.swift index 278cb5bd..59be47bd 100644 --- a/Sources/Error/RequestError.swift +++ b/Sources/Error/RequestError.swift @@ -2,7 +2,7 @@ import Foundation /// `RequestError` represents a common error that occurs while building `URLRequest` from `Request`. public enum RequestError: Error { - /// Indicates `baseUrl` of a type that conforms `Request` is invalid. + /// Indicates `baseURL` of a type that conforms `Request` is invalid. case invalidBaseURL(URL) /// Indicates `URLRequest` built by `Request.buildURLRequest` is unexpected. diff --git a/Sources/Request.swift b/Sources/Request.swift index 49f9c941..935c79c5 100644 --- a/Sources/Request.swift +++ b/Sources/Request.swift @@ -4,7 +4,7 @@ import Result /// `Request` protocol represents a request for Web API. /// Following 5 items must be implemented. /// - `typealias Response` -/// - `var baseUrl: URL` +/// - `var baseURL: URL` /// - `var method: HTTPMethod` /// - `var path: String` /// - `func response(from object: Any, urlResponse: HTTPURLResponse) throws -> Response` @@ -13,7 +13,7 @@ public protocol Request { associatedtype Response /// The base URL. - var baseUrl: URL { get } + var baseURL: URL { get } /// The HTTP request method. var method: HTTPMethod { get } @@ -104,9 +104,9 @@ public extension Request { /// Builds `URLRequest` from properties of `self`. /// - Throws: `RequestError`, `ErrorType` public func buildURLRequest() throws -> URLRequest { - let url = path.isEmpty ? baseUrl : baseUrl.appendingPathComponent(path) + let url = path.isEmpty ? baseURL : baseURL.appendingPathComponent(path) guard var components = URLComponents(url: url, resolvingAgainstBaseURL: true) else { - throw RequestError.invalidBaseURL(baseUrl) + throw RequestError.invalidBaseURL(baseURL) } var urlRequest = URLRequest(url: url) diff --git a/Tests/APIKit/BodyParametersType/MultipartFormDataParametersTests.swift b/Tests/APIKit/BodyParametersType/MultipartFormDataParametersTests.swift index 2178854b..78345a8a 100644 --- a/Tests/APIKit/BodyParametersType/MultipartFormDataParametersTests.swift +++ b/Tests/APIKit/BodyParametersType/MultipartFormDataParametersTests.swift @@ -71,8 +71,8 @@ class MultipartFormDataParametersTests: XCTestCase { // MARK: Values func testFileValue() { - let fileUrl = Bundle(for: type(of: self)).url(forResource: "test", withExtension: "json")! - let part = try! MultipartFormDataBodyParameters.Part(fileUrl: fileUrl, name: "test") + let fileURL = Bundle(for: type(of: self)).url(forResource: "test", withExtension: "json")! + let part = try! MultipartFormDataBodyParameters.Part(fileURL: fileURL, name: "test") let parameters = MultipartFormDataBodyParameters(parts: [part]) do { @@ -81,7 +81,7 @@ class MultipartFormDataParametersTests: XCTestCase { return } - let testData = try! Data(contentsOf: fileUrl) + let testData = try! Data(contentsOf: fileURL) let testString = String(data: testData, encoding: .utf8)! let encodedData = String(data: data, encoding:.utf8)! diff --git a/Tests/APIKit/RequestTests.swift b/Tests/APIKit/RequestTests.swift index 617cb9e9..bd10942b 100644 --- a/Tests/APIKit/RequestTests.swift +++ b/Tests/APIKit/RequestTests.swift @@ -58,353 +58,353 @@ class RequestTests: XCTestCase { } func testBuildURL() { - // MARK: - baseUrl = https://example.com + // MARK: - baseURL = https://example.com XCTAssertEqual( - TestRequest(baseUrl: "https://example.com", path: "").absoluteUrl, + TestRequest(baseURL: "https://example.com", path: "").absoluteURL, URL(string: "https://example.com") ) XCTAssertEqual( - TestRequest(baseUrl: "https://example.com", path: "/").absoluteUrl, + TestRequest(baseURL: "https://example.com", path: "/").absoluteURL, URL(string: "https://example.com/") ) XCTAssertEqual( - TestRequest(baseUrl: "https://example.com", path: "/", parameters: ["p": 1]).absoluteUrl, + TestRequest(baseURL: "https://example.com", path: "/", parameters: ["p": 1]).absoluteURL, URL(string: "https://example.com/?p=1") ) XCTAssertEqual( - TestRequest(baseUrl: "https://example.com", path: "foo").absoluteUrl, + TestRequest(baseURL: "https://example.com", path: "foo").absoluteURL, URL(string: "https://example.com/foo") ) XCTAssertEqual( - TestRequest(baseUrl: "https://example.com", path: "/foo", parameters: ["p": 1]).absoluteUrl, + TestRequest(baseURL: "https://example.com", path: "/foo", parameters: ["p": 1]).absoluteURL, URL(string: "https://example.com/foo?p=1") ) XCTAssertEqual( - TestRequest(baseUrl: "https://example.com", path: "/foo/").absoluteUrl, + TestRequest(baseURL: "https://example.com", path: "/foo/").absoluteURL, URL(string: "https://example.com/foo/") ) XCTAssertEqual( - TestRequest(baseUrl: "https://example.com", path: "/foo/", parameters: ["p": 1]).absoluteUrl, + TestRequest(baseURL: "https://example.com", path: "/foo/", parameters: ["p": 1]).absoluteURL, URL(string: "https://example.com/foo/?p=1") ) XCTAssertEqual( - TestRequest(baseUrl: "https://example.com", path: "foo/bar").absoluteUrl, + TestRequest(baseURL: "https://example.com", path: "foo/bar").absoluteURL, URL(string: "https://example.com/foo/bar") ) XCTAssertEqual( - TestRequest(baseUrl: "https://example.com", path: "/foo/bar").absoluteUrl, + TestRequest(baseURL: "https://example.com", path: "/foo/bar").absoluteURL, URL(string: "https://example.com/foo/bar") ) XCTAssertEqual( - TestRequest(baseUrl: "https://example.com", path: "/foo/bar", parameters: ["p": 1]).absoluteUrl, + TestRequest(baseURL: "https://example.com", path: "/foo/bar", parameters: ["p": 1]).absoluteURL, URL(string: "https://example.com/foo/bar?p=1") ) XCTAssertEqual( - TestRequest(baseUrl: "https://example.com", path: "/foo/bar/").absoluteUrl, + TestRequest(baseURL: "https://example.com", path: "/foo/bar/").absoluteURL, URL(string: "https://example.com/foo/bar/") ) XCTAssertEqual( - TestRequest(baseUrl: "https://example.com", path: "/foo/bar/", parameters: ["p": 1]).absoluteUrl, + TestRequest(baseURL: "https://example.com", path: "/foo/bar/", parameters: ["p": 1]).absoluteURL, URL(string: "https://example.com/foo/bar/?p=1") ) XCTAssertEqual( - TestRequest(baseUrl: "https://example.com", path: "/foo/bar//").absoluteUrl, + TestRequest(baseURL: "https://example.com", path: "/foo/bar//").absoluteURL, URL(string: "https://example.com/foo/bar//") ) - // MARK: - baseUrl = https://example.com/ + // MARK: - baseURL = https://example.com/ XCTAssertEqual( - TestRequest(baseUrl: "https://example.com/", path: "").absoluteUrl, + TestRequest(baseURL: "https://example.com/", path: "").absoluteURL, URL(string: "https://example.com/") ) XCTAssertEqual( - TestRequest(baseUrl: "https://example.com/", path: "/").absoluteUrl, + TestRequest(baseURL: "https://example.com/", path: "/").absoluteURL, URL(string: "https://example.com//") ) XCTAssertEqual( - TestRequest(baseUrl: "https://example.com/", path: "/", parameters: ["p": 1]).absoluteUrl, + TestRequest(baseURL: "https://example.com/", path: "/", parameters: ["p": 1]).absoluteURL, URL(string: "https://example.com//?p=1") ) XCTAssertEqual( - TestRequest(baseUrl: "https://example.com/", path: "foo").absoluteUrl, + TestRequest(baseURL: "https://example.com/", path: "foo").absoluteURL, URL(string: "https://example.com/foo") ) XCTAssertEqual( - TestRequest(baseUrl: "https://example.com/", path: "/foo").absoluteUrl, + TestRequest(baseURL: "https://example.com/", path: "/foo").absoluteURL, URL(string: "https://example.com//foo") ) XCTAssertEqual( - TestRequest(baseUrl: "https://example.com/", path: "/foo", parameters: ["p": 1]).absoluteUrl, + TestRequest(baseURL: "https://example.com/", path: "/foo", parameters: ["p": 1]).absoluteURL, URL(string: "https://example.com//foo?p=1") ) XCTAssertEqual( - TestRequest(baseUrl: "https://example.com/", path: "/foo/").absoluteUrl, + TestRequest(baseURL: "https://example.com/", path: "/foo/").absoluteURL, URL(string: "https://example.com//foo/") ) XCTAssertEqual( - TestRequest(baseUrl: "https://example.com/", path: "/foo/", parameters: ["p": 1]).absoluteUrl, + TestRequest(baseURL: "https://example.com/", path: "/foo/", parameters: ["p": 1]).absoluteURL, URL(string: "https://example.com//foo/?p=1") ) XCTAssertEqual( - TestRequest(baseUrl: "https://example.com/", path: "foo/bar").absoluteUrl, + TestRequest(baseURL: "https://example.com/", path: "foo/bar").absoluteURL, URL(string: "https://example.com/foo/bar") ) XCTAssertEqual( - TestRequest(baseUrl: "https://example.com/", path: "/foo/bar").absoluteUrl, + TestRequest(baseURL: "https://example.com/", path: "/foo/bar").absoluteURL, URL(string: "https://example.com//foo/bar") ) XCTAssertEqual( - TestRequest(baseUrl: "https://example.com/", path: "/foo/bar", parameters: ["p": 1]).absoluteUrl, + TestRequest(baseURL: "https://example.com/", path: "/foo/bar", parameters: ["p": 1]).absoluteURL, URL(string: "https://example.com//foo/bar?p=1") ) XCTAssertEqual( - TestRequest(baseUrl: "https://example.com/", path: "/foo/bar/").absoluteUrl, + TestRequest(baseURL: "https://example.com/", path: "/foo/bar/").absoluteURL, URL(string: "https://example.com//foo/bar/") ) XCTAssertEqual( - TestRequest(baseUrl: "https://example.com/", path: "/foo/bar/", parameters: ["p": 1]).absoluteUrl, + TestRequest(baseURL: "https://example.com/", path: "/foo/bar/", parameters: ["p": 1]).absoluteURL, URL(string: "https://example.com//foo/bar/?p=1") ) XCTAssertEqual( - TestRequest(baseUrl: "https://example.com/", path: "foo//bar//").absoluteUrl, + TestRequest(baseURL: "https://example.com/", path: "foo//bar//").absoluteURL, URL(string: "https://example.com/foo//bar//") ) - // MARK: - baseUrl = https://example.com/api + // MARK: - baseURL = https://example.com/api XCTAssertEqual( - TestRequest(baseUrl: "https://example.com/api", path: "").absoluteUrl, + TestRequest(baseURL: "https://example.com/api", path: "").absoluteURL, URL(string: "https://example.com/api") ) XCTAssertEqual( - TestRequest(baseUrl: "https://example.com/api", path: "/").absoluteUrl, + TestRequest(baseURL: "https://example.com/api", path: "/").absoluteURL, URL(string: "https://example.com/api/") ) XCTAssertEqual( - TestRequest(baseUrl: "https://example.com/api", path: "/", parameters: ["p": 1]).absoluteUrl, + TestRequest(baseURL: "https://example.com/api", path: "/", parameters: ["p": 1]).absoluteURL, URL(string: "https://example.com/api/?p=1") ) XCTAssertEqual( - TestRequest(baseUrl: "https://example.com/api", path: "foo").absoluteUrl, + TestRequest(baseURL: "https://example.com/api", path: "foo").absoluteURL, URL(string: "https://example.com/api/foo") ) XCTAssertEqual( - TestRequest(baseUrl: "https://example.com/api", path: "/foo").absoluteUrl, + TestRequest(baseURL: "https://example.com/api", path: "/foo").absoluteURL, URL(string: "https://example.com/api/foo") ) XCTAssertEqual( - TestRequest(baseUrl: "https://example.com/api", path: "/foo", parameters: ["p": 1]).absoluteUrl, + TestRequest(baseURL: "https://example.com/api", path: "/foo", parameters: ["p": 1]).absoluteURL, URL(string: "https://example.com/api/foo?p=1") ) XCTAssertEqual( - TestRequest(baseUrl: "https://example.com/api", path: "/foo/").absoluteUrl, + TestRequest(baseURL: "https://example.com/api", path: "/foo/").absoluteURL, URL(string: "https://example.com/api/foo/") ) XCTAssertEqual( - TestRequest(baseUrl: "https://example.com/api", path: "/foo/", parameters: ["p": 1]).absoluteUrl, + TestRequest(baseURL: "https://example.com/api", path: "/foo/", parameters: ["p": 1]).absoluteURL, URL(string: "https://example.com/api/foo/?p=1") ) XCTAssertEqual( - TestRequest(baseUrl: "https://example.com/api", path: "foo/bar").absoluteUrl, + TestRequest(baseURL: "https://example.com/api", path: "foo/bar").absoluteURL, URL(string: "https://example.com/api/foo/bar") ) XCTAssertEqual( - TestRequest(baseUrl: "https://example.com/api", path: "/foo/bar").absoluteUrl, + TestRequest(baseURL: "https://example.com/api", path: "/foo/bar").absoluteURL, URL(string: "https://example.com/api/foo/bar") ) XCTAssertEqual( - TestRequest(baseUrl: "https://example.com/api", path: "/foo/bar", parameters: ["p": 1]).absoluteUrl, + TestRequest(baseURL: "https://example.com/api", path: "/foo/bar", parameters: ["p": 1]).absoluteURL, URL(string: "https://example.com/api/foo/bar?p=1") ) XCTAssertEqual( - TestRequest(baseUrl: "https://example.com/api", path: "/foo/bar/").absoluteUrl, + TestRequest(baseURL: "https://example.com/api", path: "/foo/bar/").absoluteURL, URL(string: "https://example.com/api/foo/bar/") ) XCTAssertEqual( - TestRequest(baseUrl: "https://example.com/api", path: "/foo/bar/", parameters: ["p": 1]).absoluteUrl, + TestRequest(baseURL: "https://example.com/api", path: "/foo/bar/", parameters: ["p": 1]).absoluteURL, URL(string: "https://example.com/api/foo/bar/?p=1") ) XCTAssertEqual( - TestRequest(baseUrl: "https://example.com/api", path: "foo//bar//").absoluteUrl, + TestRequest(baseURL: "https://example.com/api", path: "foo//bar//").absoluteURL, URL(string: "https://example.com/api/foo//bar//") ) - // MARK: - baseUrl = https://example.com/api/ + // MARK: - baseURL = https://example.com/api/ XCTAssertEqual( - TestRequest(baseUrl: "https://example.com/api/", path: "").absoluteUrl, + TestRequest(baseURL: "https://example.com/api/", path: "").absoluteURL, URL(string: "https://example.com/api/") ) XCTAssertEqual( - TestRequest(baseUrl: "https://example.com/api/", path: "/").absoluteUrl, + TestRequest(baseURL: "https://example.com/api/", path: "/").absoluteURL, URL(string: "https://example.com/api//") ) XCTAssertEqual( - TestRequest(baseUrl: "https://example.com/api/", path: "/", parameters: ["p": 1]).absoluteUrl, + TestRequest(baseURL: "https://example.com/api/", path: "/", parameters: ["p": 1]).absoluteURL, URL(string: "https://example.com/api//?p=1") ) XCTAssertEqual( - TestRequest(baseUrl: "https://example.com/api/", path: "foo").absoluteUrl, + TestRequest(baseURL: "https://example.com/api/", path: "foo").absoluteURL, URL(string: "https://example.com/api/foo") ) XCTAssertEqual( - TestRequest(baseUrl: "https://example.com/api/", path: "/foo").absoluteUrl, + TestRequest(baseURL: "https://example.com/api/", path: "/foo").absoluteURL, URL(string: "https://example.com/api//foo") ) XCTAssertEqual( - TestRequest(baseUrl: "https://example.com/api/", path: "/foo", parameters: ["p": 1]).absoluteUrl, + TestRequest(baseURL: "https://example.com/api/", path: "/foo", parameters: ["p": 1]).absoluteURL, URL(string: "https://example.com/api//foo?p=1") ) XCTAssertEqual( - TestRequest(baseUrl: "https://example.com/api/", path: "/foo/").absoluteUrl, + TestRequest(baseURL: "https://example.com/api/", path: "/foo/").absoluteURL, URL(string: "https://example.com/api//foo/") ) XCTAssertEqual( - TestRequest(baseUrl: "https://example.com/api/", path: "/foo/", parameters: ["p": 1]).absoluteUrl, + TestRequest(baseURL: "https://example.com/api/", path: "/foo/", parameters: ["p": 1]).absoluteURL, URL(string: "https://example.com/api//foo/?p=1") ) XCTAssertEqual( - TestRequest(baseUrl: "https://example.com/api/", path: "foo/bar").absoluteUrl, + TestRequest(baseURL: "https://example.com/api/", path: "foo/bar").absoluteURL, URL(string: "https://example.com/api/foo/bar") ) XCTAssertEqual( - TestRequest(baseUrl: "https://example.com/api/", path: "/foo/bar").absoluteUrl, + TestRequest(baseURL: "https://example.com/api/", path: "/foo/bar").absoluteURL, URL(string: "https://example.com/api//foo/bar") ) XCTAssertEqual( - TestRequest(baseUrl: "https://example.com/api/", path: "/foo/bar", parameters: ["p": 1]).absoluteUrl, + TestRequest(baseURL: "https://example.com/api/", path: "/foo/bar", parameters: ["p": 1]).absoluteURL, URL(string: "https://example.com/api//foo/bar?p=1") ) XCTAssertEqual( - TestRequest(baseUrl: "https://example.com/api/", path: "/foo/bar/").absoluteUrl, + TestRequest(baseURL: "https://example.com/api/", path: "/foo/bar/").absoluteURL, URL(string: "https://example.com/api//foo/bar/") ) XCTAssertEqual( - TestRequest(baseUrl: "https://example.com/api/", path: "/foo/bar/", parameters: ["p": 1]).absoluteUrl, + TestRequest(baseURL: "https://example.com/api/", path: "/foo/bar/", parameters: ["p": 1]).absoluteURL, URL(string: "https://example.com/api//foo/bar/?p=1") ) XCTAssertEqual( - TestRequest(baseUrl: "https://example.com/api/", path: "foo//bar//").absoluteUrl, + TestRequest(baseURL: "https://example.com/api/", path: "foo//bar//").absoluteURL, URL(string: "https://example.com/api/foo//bar//") ) - // MARK: - baseUrl = https://example.com/// + // MARK: - baseURL = https://example.com/// XCTAssertEqual( - TestRequest(baseUrl: "https://example.com///", path: "").absoluteUrl, + TestRequest(baseURL: "https://example.com///", path: "").absoluteURL, URL(string: "https://example.com///") ) XCTAssertEqual( - TestRequest(baseUrl: "https://example.com///", path: "/").absoluteUrl, + TestRequest(baseURL: "https://example.com///", path: "/").absoluteURL, URL(string: "https://example.com////") ) XCTAssertEqual( - TestRequest(baseUrl: "https://example.com///", path: "/", parameters: ["p": 1]).absoluteUrl, + TestRequest(baseURL: "https://example.com///", path: "/", parameters: ["p": 1]).absoluteURL, URL(string: "https://example.com////?p=1") ) XCTAssertEqual( - TestRequest(baseUrl: "https://example.com///", path: "foo").absoluteUrl, + TestRequest(baseURL: "https://example.com///", path: "foo").absoluteURL, URL(string: "https://example.com///foo") ) XCTAssertEqual( - TestRequest(baseUrl: "https://example.com///", path: "/foo").absoluteUrl, + TestRequest(baseURL: "https://example.com///", path: "/foo").absoluteURL, URL(string: "https://example.com////foo") ) XCTAssertEqual( - TestRequest(baseUrl: "https://example.com///", path: "/foo", parameters: ["p": 1]).absoluteUrl, + TestRequest(baseURL: "https://example.com///", path: "/foo", parameters: ["p": 1]).absoluteURL, URL(string: "https://example.com////foo?p=1") ) XCTAssertEqual( - TestRequest(baseUrl: "https://example.com///", path: "/foo/").absoluteUrl, + TestRequest(baseURL: "https://example.com///", path: "/foo/").absoluteURL, URL(string: "https://example.com////foo/") ) XCTAssertEqual( - TestRequest(baseUrl: "https://example.com///", path: "/foo/", parameters: ["p": 1]).absoluteUrl, + TestRequest(baseURL: "https://example.com///", path: "/foo/", parameters: ["p": 1]).absoluteURL, URL(string: "https://example.com////foo/?p=1") ) XCTAssertEqual( - TestRequest(baseUrl: "https://example.com///", path: "foo/bar").absoluteUrl, + TestRequest(baseURL: "https://example.com///", path: "foo/bar").absoluteURL, URL(string: "https://example.com///foo/bar") ) XCTAssertEqual( - TestRequest(baseUrl: "https://example.com///", path: "/foo/bar").absoluteUrl, + TestRequest(baseURL: "https://example.com///", path: "/foo/bar").absoluteURL, URL(string: "https://example.com////foo/bar") ) XCTAssertEqual( - TestRequest(baseUrl: "https://example.com///", path: "/foo/bar", parameters: ["p": 1]).absoluteUrl, + TestRequest(baseURL: "https://example.com///", path: "/foo/bar", parameters: ["p": 1]).absoluteURL, URL(string: "https://example.com////foo/bar?p=1") ) XCTAssertEqual( - TestRequest(baseUrl: "https://example.com///", path: "/foo/bar/").absoluteUrl, + TestRequest(baseURL: "https://example.com///", path: "/foo/bar/").absoluteURL, URL(string: "https://example.com////foo/bar/") ) XCTAssertEqual( - TestRequest(baseUrl: "https://example.com///", path: "/foo/bar/", parameters: ["p": 1]).absoluteUrl, + TestRequest(baseURL: "https://example.com///", path: "/foo/bar/", parameters: ["p": 1]).absoluteURL, URL(string: "https://example.com////foo/bar/?p=1") ) XCTAssertEqual( - TestRequest(baseUrl: "https://example.com///", path: "foo//bar//").absoluteUrl, + TestRequest(baseURL: "https://example.com///", path: "foo//bar//").absoluteURL, URL(string: "https://example.com///foo//bar//") ) } diff --git a/Tests/APIKit/SessionTests.swift b/Tests/APIKit/SessionTests.swift index 4a45c915..7d154284 100644 --- a/Tests/APIKit/SessionTests.swift +++ b/Tests/APIKit/SessionTests.swift @@ -179,7 +179,7 @@ class SessionTests: XCTestCase { struct AnotherTestRequest: Request { typealias Response = Void - var baseUrl: URL { + var baseURL: URL { return URL(string: "https://example.com")! } diff --git a/Tests/APIKit/TestComponents/TestRequest.swift b/Tests/APIKit/TestComponents/TestRequest.swift index bf6e6a58..e3bc69aa 100644 --- a/Tests/APIKit/TestComponents/TestRequest.swift +++ b/Tests/APIKit/TestComponents/TestRequest.swift @@ -2,7 +2,7 @@ import Foundation import APIKit struct TestRequest: Request { - var absoluteUrl: URL? { + var absoluteURL: URL? { let urlRequest = try? buildURLRequest() return urlRequest?.url } @@ -10,8 +10,8 @@ struct TestRequest: Request { // MARK: Request typealias Response = Any - init(baseUrl: String = "https://example.com", path: String = "/", method: HTTPMethod = .get, parameters: Any? = [:], headerFields: [String: String] = [:], interceptURLRequest: @escaping (URLRequest) throws -> URLRequest = { $0 }) { - self.baseUrl = URL(string: baseUrl)! + init(baseURL: String = "https://example.com", path: String = "/", method: HTTPMethod = .get, parameters: Any? = [:], headerFields: [String: String] = [:], interceptURLRequest: @escaping (URLRequest) throws -> URLRequest = { $0 }) { + self.baseURL = URL(string: baseURL)! self.path = path self.method = method self.parameters = parameters @@ -19,7 +19,7 @@ struct TestRequest: Request { self.interceptURLRequest = interceptURLRequest } - let baseUrl: URL + let baseURL: URL let method: HTTPMethod let path: String let parameters: Any? From 8de24dbbe50df1e0264b2be6d7233c2f6e1c3491 Mon Sep 17 00:00:00 2001 From: Syo Ikeda Date: Fri, 16 Sep 2016 14:59:31 +0900 Subject: [PATCH 38/38] Fix a documentation --- Sources/Request.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Sources/Request.swift b/Sources/Request.swift index 935c79c5..30610937 100644 --- a/Sources/Request.swift +++ b/Sources/Request.swift @@ -56,7 +56,7 @@ public protocol Request { func intercept(object: Any, urlResponse: HTTPURLResponse) throws -> Any /// Build `Response` instance from raw response object. This method is called after - /// `interceptObject(:URLResponse:)` if it does not throw any error. + /// `intercept(object:urlResponse:)` if it does not throw any error. /// - Throws: `ErrorType` func response(from object: Any, urlResponse: HTTPURLResponse) throws -> Response }