diff --git a/.swiftlint.yml b/.swiftlint.yml new file mode 100644 index 0000000..c3043ee --- /dev/null +++ b/.swiftlint.yml @@ -0,0 +1,25 @@ +disabled_rules: +- trailing_whitespace # this would rewrite every single file :/ +- large_tuple +- type_name + +opt_in_rules: +- empty_count +- attributes +- closure_spacing +- conditional_returns_on_newline +- overridden_super_call +- private_outlet +- private_unit_test +- prohibited_super_call +- redundant_nil_coalescing +- switch_case_on_newline +- sorted_imports +- first_where +- closure_end_indentation + +variable_name: + min_length: 1 + +excluded: + - Carthage diff --git a/Cartfile b/Cartfile index 1fa3010..ad0e5ad 100644 --- a/Cartfile +++ b/Cartfile @@ -1,3 +1,3 @@ -github "Alamofire/Alamofire" "4.3.0" -github "s4cha/Arrow" "3.0.3" -github "s4cha/then" "2.0.2" +github "Alamofire/Alamofire" "4.4.0" +github "freshOS/Arrow" "3.0.5" +github "freshOS/then" "2.2.2" diff --git a/Cartfile.resolved b/Cartfile.resolved index 1fa3010..ad0e5ad 100644 --- a/Cartfile.resolved +++ b/Cartfile.resolved @@ -1,3 +1,3 @@ -github "Alamofire/Alamofire" "4.3.0" -github "s4cha/Arrow" "3.0.3" -github "s4cha/then" "2.0.2" +github "Alamofire/Alamofire" "4.4.0" +github "freshOS/Arrow" "3.0.5" +github "freshOS/then" "2.2.2" diff --git a/Carthage/Checkouts/Alamofire b/Carthage/Checkouts/Alamofire index c9c9d09..d1f0b86 160000 --- a/Carthage/Checkouts/Alamofire +++ b/Carthage/Checkouts/Alamofire @@ -1 +1 @@ -Subproject commit c9c9d091b308a57ff9a744be4f2537ac9c5b4c0b +Subproject commit d1f0b86de9cae2b4d860795a8a253905909038e8 diff --git a/Carthage/Checkouts/Arrow b/Carthage/Checkouts/Arrow index 18889f2..8a398d7 160000 --- a/Carthage/Checkouts/Arrow +++ b/Carthage/Checkouts/Arrow @@ -1 +1 @@ -Subproject commit 18889f2da91817e095c9acfb8f6c305a1a754c28 +Subproject commit 8a398d725f6bab7846e04b5e811091b1d59cc352 diff --git a/Carthage/Checkouts/then b/Carthage/Checkouts/then index 7754024..24e07df 160000 --- a/Carthage/Checkouts/then +++ b/Carthage/Checkouts/then @@ -1 +1 @@ -Subproject commit 77540243af8d92f5fe88deaf0c49f3b1dc847fee +Subproject commit 24e07df982885cbfba06415f25e562fe2aac72ba diff --git a/ws.framework.zip b/ws.framework.zip deleted file mode 100644 index 4a7200f..0000000 Binary files a/ws.framework.zip and /dev/null differ diff --git a/ws.xcodeproj/project.pbxproj b/ws.xcodeproj/project.pbxproj index 0d47153..db044f1 100644 --- a/ws.xcodeproj/project.pbxproj +++ b/ws.xcodeproj/project.pbxproj @@ -298,6 +298,7 @@ isa = PBXNativeTarget; buildConfigurationList = 996CABA41BF67A7C00931EAD /* Build configuration list for PBXNativeTarget "ws" */; buildPhases = ( + 9925B8D81E9FB07A002C081D /* ShellScript */, 996CAB8B1BF67A7C00931EAD /* Sources */, 996CAB8C1BF67A7C00931EAD /* Frameworks */, 996CAB8D1BF67A7C00931EAD /* Headers */, @@ -480,6 +481,22 @@ }; /* End PBXResourcesBuildPhase section */ +/* Begin PBXShellScriptBuildPhase section */ + 9925B8D81E9FB07A002C081D /* ShellScript */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + ); + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "if which swiftlint >/dev/null; then\nswiftlint\nelse\necho \"warning: SwiftLint not installed, download from https://github.com/realm/SwiftLint\"\nfi"; + }; +/* End PBXShellScriptBuildPhase section */ + /* Begin PBXSourcesBuildPhase section */ 996CAB8B1BF67A7C00931EAD /* Sources */ = { isa = PBXSourcesBuildPhase; diff --git a/ws/WS+Requests.swift b/ws/WS+Requests.swift index 27a127a..ef26fb4 100644 --- a/ws/WS+Requests.swift +++ b/ws/WS+Requests.swift @@ -10,23 +10,28 @@ import Foundation extension WS { - public func getRequest(_ url:String, params:[String:Any] = [String:Any]()) -> WSRequest { + public func getRequest(_ url: String, params: [String:Any] = [String: Any]()) -> WSRequest { return call(url, verb: .get, params: params) } - public func putRequest(_ url:String, params:[String:Any] = [String:Any]()) -> WSRequest { + public func putRequest(_ url: String, params: [String:Any] = [String: Any]()) -> WSRequest { return call(url, verb: .put, params: params) } - public func postRequest(_ url:String, params:[String:Any] = [String:Any]()) -> WSRequest { + public func postRequest(_ url: String, params: [String: Any] = [String: Any]()) -> WSRequest { return call(url, verb: .post, params: params) } - public func deleteRequest(_ url:String, params:[String:Any] = [String:Any]()) -> WSRequest { + public func deleteRequest(_ url: String, params: [String: Any] = [String: Any]()) -> WSRequest { return call(url, verb: .delete, params: params) } - public func postMultipartRequest(_ url:String, params:[String:Any] = [String:Any](), name:String, data:Data, fileName:String, mimeType:String) -> WSRequest { + public func postMultipartRequest(_ url: String, + params: [String: Any] = [String: Any](), + name: String, + data: Data, + fileName: String, + mimeType: String) -> WSRequest { let c = call(url, verb: .post, params: params) c.isMultipart = true c.multipartData = data @@ -36,7 +41,12 @@ extension WS { return c } - public func putMultipartRequest(_ url:String, params:[String:Any] = [String:Any](), name:String, data:Data, fileName:String, mimeType:String) -> WSRequest { + public func putMultipartRequest(_ url: String, + params: [String: Any] = [String: Any](), + name: String, + data: Data, + fileName: String, + mimeType: String) -> WSRequest { let c = call(url, verb: .put, params: params) c.isMultipart = true c.multipartData = data diff --git a/ws/WS+TypedCalls.swift b/ws/WS+TypedCalls.swift index 5561ebc..1ecab90 100644 --- a/ws/WS+TypedCalls.swift +++ b/ws/WS+TypedCalls.swift @@ -6,37 +6,50 @@ // Copyright © 2016 s4cha. All rights reserved. // -import Foundation import Arrow +import Foundation import then - extension WS { - public func get(_ url: String, params: [String: Any] = [String: Any](), keypath: String? = nil) -> Promise<[T]> { + public func get(_ url: String, + params: [String: Any] = [String: Any](), + keypath: String? = nil) -> Promise<[T]> { let keypath = keypath ?? defaultCollectionParsingKeyPath - return getRequest(url, params: params).fetch().registerThen { (json: JSON) -> [T] in - WSModelJSONParser().toModels(json, keypath: keypath) + return getRequest(url, params: params).fetch() + .registerThen { (json: JSON) -> [T] in + WSModelJSONParser().toModels(json, keypath: keypath) }.resolveOnMainThread() } - public func get(_ url: String, params: [String: Any] = [String: Any](), keypath: String? = nil) -> Promise { + public func get(_ url: String, + params: [String: Any] = [String: Any](), + keypath: String? = nil) -> Promise { return resourceCall(.get, url: url, params: params, keypath: keypath) } - public func post(_ url: String, params: [String: Any] = [String: Any](), keypath: String? = nil) -> Promise { + public func post(_ url: String, + params: [String: Any] = [String: Any](), + keypath: String? = nil) -> Promise { return resourceCall(.post, url: url, params: params, keypath: keypath) } - public func put(_ url: String, params: [String: Any] = [String: Any](), keypath: String? = nil) -> Promise { + public func put(_ url: String, + params: [String: Any] = [String: Any](), + keypath: String? = nil) -> Promise { return resourceCall(.put, url: url, params: params, keypath: keypath) } - public func delete(_ url: String, params: [String: Any] = [String: Any](), keypath: String? = nil) -> Promise { + public func delete(_ url: String, + params: [String: Any] = [String: Any](), + keypath: String? = nil) -> Promise { return resourceCall(.delete, url: url, params: params, keypath: keypath) } - private func resourceCall(_ verb: WSHTTPVerb, url: String, params: [String: Any] = [String: Any](), keypath: String? = nil) -> Promise { + private func resourceCall(_ verb: WSHTTPVerb, + url: String, + params: [String: Any] = [String: Any](), + keypath: String? = nil) -> Promise { let c = defaultCall() c.httpVerb = verb c.URL = url @@ -52,51 +65,68 @@ extension WS { extension WS { - public func get(_ url: String, params: [String: Any] = [String: Any](), keypath: String? = nil) -> Promise<[T]> { + public func get(_ url: String, + params: [String: Any] = [String: Any](), + keypath: String? = nil) -> Promise<[T]> { let keypath = keypath ?? defaultCollectionParsingKeyPath - return getRequest(url, params: params).fetch().registerThen { (json: JSON) in - Promise<[T]> { (resolve, reject) in - if let t: [T] = WSModelJSONParser().toModels(json, keypath: keypath) { - resolve(t) - } else { - reject(WSError.unableToParseResponse) + return getRequest(url, params: params) + .fetch() + .registerThen { (json: JSON) in + Promise<[T]> { (resolve, reject) in + if let t: [T] = WSModelJSONParser().toModels(json, keypath: keypath) { + resolve(t) + } else { + reject(WSError.unableToParseResponse) + } } } - }.resolveOnMainThread() + .resolveOnMainThread() } - public func get(_ url: String, params: [String: Any] = [String: Any](), keypath: String? = nil) -> Promise { + public func get(_ url: String, + params: [String: Any] = [String: Any](), + keypath: String? = nil) -> Promise { return typeCall(.get, url: url, params: params, keypath: keypath) } - public func post(_ url: String, params: [String: Any] = [String: Any](), keypath: String? = nil) -> Promise { + public func post(_ url: String, + params: [String: Any] = [String: Any](), + keypath: String? = nil) -> Promise { return typeCall(.post, url: url, params: params, keypath: keypath) } - public func put(_ url: String, params: [String: Any] = [String: Any](), keypath: String? = nil) -> Promise { + public func put(_ url: String, + params: [String: Any] = [String: Any](), + keypath: String? = nil) -> Promise { return typeCall(.put, url: url, params: params, keypath: keypath) } - public func delete(_ url: String, params: [String: Any] = [String: Any](), keypath: String? = nil) -> Promise { + public func delete(_ url: String, + params: [String: Any] = [String: Any](), + keypath: String? = nil) -> Promise { return typeCall(.delete, url: url, params: params, keypath: keypath) } - private func typeCall(_ verb: WSHTTPVerb, url: String, params: [String: Any] = [String: Any](), keypath: String? = nil) -> Promise { + private func typeCall(_ verb: WSHTTPVerb, + url: String, params: [String: Any] = [String: Any](), + keypath: String? = nil) -> Promise { let c = defaultCall() c.httpVerb = verb c.URL = url c.params = params // Apply corresponding JSON mapper - return c.fetch().registerThen { (json: JSON) in - Promise { (resolve, reject) in - if let t: T = WSModelJSONParser().toModel(json, keypath: keypath) { - resolve(t) - } else { - reject(WSError.unableToParseResponse) + return c.fetch() + .registerThen { (json: JSON) in + Promise { (resolve, reject) in + if let t: T = WSModelJSONParser().toModel(json, keypath: keypath) { + resolve(t) + } else { + reject(WSError.unableToParseResponse) + } } } - }.resolveOnMainThread() + .resolveOnMainThread() } } diff --git a/ws/WS.swift b/ws/WS.swift index 2868020..300c3e0 100644 --- a/ws/WS.swift +++ b/ws/WS.swift @@ -6,9 +6,9 @@ // Copyright © 2015 s4cha. All rights reserved. // -import Foundation import Alamofire import Arrow +import Foundation import then open class WS { @@ -19,11 +19,10 @@ open class WS { This is overidden by the per-request keypath if present. */ - open var defaultCollectionParsingKeyPath:String? = nil + open var defaultCollectionParsingKeyPath: String? @available(*, unavailable, renamed:"defaultCollectionParsingKeyPath") - open var jsonParsingColletionKey:String? = nil - + open var jsonParsingColletionKey: String? /** Prints network calls to the console. @@ -43,7 +42,7 @@ open class WS { Custom error handler block, to parse error returned in response body. For example: `{ error: { code: 1, message: "Server error" } }` */ - open var errorHandler: ((JSON) -> Error?)? = nil + open var errorHandler: ((JSON) -> Error?)? open var baseURL = "" open var headers = [String: String]() @@ -53,13 +52,13 @@ open class WS { @param Pass the base url of your webservice, E.g : "http://jsonplaceholder.typicode.com" */ - public init(_ aBaseURL:String) { + public init(_ aBaseURL: String) { baseURL = aBaseURL } // MARK: - Calls - internal func call(_ url:String, verb:WSHTTPVerb = .get, params:[String:Any] = [String:Any]()) -> WSRequest { + internal func call(_ url: String, verb: WSHTTPVerb = .get, params: [String: Any] = [String: Any]()) -> WSRequest { let c = defaultCall() c.httpVerb = verb c.URL = url @@ -84,39 +83,39 @@ open class WS { return getRequest(url, params: params).fetch().resolveOnMainThread() } - open func post(_ url:String, params:[String:Any] = [String:Any]()) -> Promise { + open func post(_ url: String, params: [String: Any] = [String: Any]()) -> Promise { return postRequest(url, params: params).fetch().resolveOnMainThread() } - open func put(_ url:String, params:[String:Any] = [String:Any]()) -> Promise { + open func put(_ url: String, params: [String: Any] = [String: Any]()) -> Promise { return putRequest(url, params: params).fetch().resolveOnMainThread() } - open func delete(_ url:String, params:[String:Any] = [String:Any]()) -> Promise { + open func delete(_ url: String, params: [String: Any] = [String: Any]()) -> Promise { return deleteRequest(url, params: params).fetch().resolveOnMainThread() } // MARK: Void calls - open func get(_ url:String, params:[String:Any] = [String:Any]()) -> Promise { + open func get(_ url: String, params: [String: Any] = [String: Any]()) -> Promise { let r = getRequest(url, params: params) r.returnsJSON = false - return r.fetch().registerThen { (json: JSON) -> Void in }.resolveOnMainThread() + return r.fetch().registerThen { (_: JSON) -> Void in }.resolveOnMainThread() } - open func post(_ url:String, params:[String:Any] = [String:Any]()) -> Promise { + open func post(_ url: String, params: [String: Any] = [String: Any]()) -> Promise { let r = postRequest(url, params: params) r.returnsJSON = false - return r.fetch().registerThen { (json:JSON) -> Void in }.resolveOnMainThread() + return r.fetch().registerThen { (_:JSON) -> Void in }.resolveOnMainThread() } - open func put(_ url:String, params:[String:Any] = [String:Any]()) -> Promise { + open func put(_ url: String, params: [String: Any] = [String: Any]()) -> Promise { let r = putRequest(url, params: params) r.returnsJSON = false return r.fetch().registerThen { (_:JSON) -> Void in }.resolveOnMainThread() } - open func delete(_ url:String, params:[String:Any] = [String:Any]()) -> Promise { + open func delete(_ url: String, params: [String: Any] = [String: Any]()) -> Promise { let r = deleteRequest(url, params: params) r.returnsJSON = false return r.fetch().registerThen { (_: JSON) -> Void in }.resolveOnMainThread() @@ -124,24 +123,38 @@ open class WS { // MARK: - Multipart - open func postMultipart(_ url:String, params:[String:Any] = [String:Any](), name:String, data:Data, fileName:String, mimeType:String) -> Promise { - let r = postMultipartRequest(url, params:params, name:name, data: data, fileName: fileName, mimeType: mimeType) + open func postMultipart(_ url: String, + params: [String: Any] = [String: Any](), + name: String, + data: Data, + fileName: String, + mimeType: String) -> Promise { + let r = postMultipartRequest(url, + params:params, + name:name, + data: data, + fileName: fileName, + mimeType: mimeType) return r.fetch().resolveOnMainThread() } - open func putMultipart(_ url:String, params:[String:Any] = [String:Any](), name:String, data:Data, fileName:String, mimeType:String) -> Promise { + open func putMultipart(_ url: String, + params: [String: Any] = [String: Any](), + name: String, + data: Data, + fileName: String, + mimeType: String) -> Promise { let r = putMultipartRequest(url, params:params, name:name, data: data, fileName: fileName, mimeType: mimeType) return r.fetch().resolveOnMainThread() } } - public extension Promise { public func resolveOnMainThread() -> Promise { return Promise { resolve, reject, progress in - self.progress{ p in + self.progress { p in progress(p) } self.registerThen { t in diff --git a/ws/WSError.swift b/ws/WSError.swift index 21fe811..b67c824 100644 --- a/ws/WSError.swift +++ b/ws/WSError.swift @@ -6,8 +6,8 @@ // Copyright © 2016 s4cha. All rights reserved. // -import Foundation import Arrow +import Foundation public struct WSError: Error { @@ -71,7 +71,7 @@ public struct WSError: Error { public var status: Status public var code: Int { return status.rawValue } - public var jsonPayload:JSON? = nil + public var jsonPayload: JSON? public init(httpStatusCode: Int) { self.status = Status(rawValue: httpStatusCode) ?? .unknown diff --git a/ws/WSHTTPVerb.swift b/ws/WSHTTPVerb.swift index bce7a25..80688c6 100644 --- a/ws/WSHTTPVerb.swift +++ b/ws/WSHTTPVerb.swift @@ -8,7 +8,7 @@ import Foundation -public enum WSHTTPVerb:String { +public enum WSHTTPVerb: String { case get = "GET" case put = "PUT" case post = "POST" diff --git a/ws/WSLogger.swift b/ws/WSLogger.swift index a5e502e..21d7ed4 100644 --- a/ws/WSLogger.swift +++ b/ws/WSLogger.swift @@ -6,9 +6,8 @@ // Copyright © 2016 s4cha. All rights reserved. // -import Foundation import Alamofire - +import Foundation public enum WSLogLevel { @@ -24,28 +23,28 @@ public enum WSLogLevel { case debug } - class WSLogger { var logLevels = WSLogLevel.off - func logMultipartRequest(_ request:WSRequest) { + func logMultipartRequest(_ request: WSRequest) { guard logLevels != .off else { return } print("\(request.httpVerb.rawValue.uppercased()) '\(request.URL)'") print(" params : \(request.params)") - for (k,v) in request.headers { + for (k, v) in request.headers { print(" \(k) : \(v)") } - print(" name : \(request.multipartName), mimeType: \(request.multipartMimeType), filename: \(request.multipartFileName)") + print(" name : \(request.multipartName)," + + "mimeType: \(request.multipartMimeType), filename: \(request.multipartFileName)") if logLevels == .debug { print() } } - func logRequest(_ request:DataRequest) { + func logRequest(_ request: DataRequest) { guard logLevels != .off else { return } @@ -61,7 +60,7 @@ class WSLogger { } } - func logResponse(_ response:DefaultDataResponse) { + func logResponse(_ response: DefaultDataResponse) { guard logLevels != .off else { return } @@ -71,15 +70,17 @@ class WSLogger { } } - func logResponse(_ response:DataResponse) { + func logResponse(_ response: DataResponse) { guard logLevels != .off else { return } logStatusCodeAndURL(response.response) if logLevels == .debug { switch response.result { - case .success(let value): print(value) - case .failure(let error): print(error) + case .success(let value): + print(value) + case .failure(let error): + print(error) } } if logLevels == .debug { @@ -87,22 +88,22 @@ class WSLogger { } } - private func logHeaders(_ urlRequest:URLRequest) { + private func logHeaders(_ urlRequest: URLRequest) { if let allHTTPHeaderFields = urlRequest.allHTTPHeaderFields { - for (k,v) in allHTTPHeaderFields { + for (k, v) in allHTTPHeaderFields { print(" \(k) : \(v)") } } } - private func logBody(_ urlRequest:URLRequest) { + private func logBody(_ urlRequest: URLRequest) { if let body = urlRequest.httpBody, let str = String(data:body, encoding: .utf8) { print(" HttpBody : \(str)") } } - private func logStatusCodeAndURL(_ urlResponse:HTTPURLResponse?) { + private func logStatusCodeAndURL(_ urlResponse: HTTPURLResponse?) { if let urlResponse = urlResponse, let url = urlResponse.url { print("\(urlResponse.statusCode) '\(url.absoluteString)'") } diff --git a/ws/WSModelJSONParser.swift b/ws/WSModelJSONParser.swift index df38059..ec0df95 100644 --- a/ws/WSModelJSONParser.swift +++ b/ws/WSModelJSONParser.swift @@ -6,8 +6,8 @@ // Copyright © 2016 s4cha. All rights reserved. // -import Foundation import Arrow +import Foundation open class WSModelJSONParser { @@ -29,7 +29,7 @@ extension WSModelJSONParser where T: ArrowInitializable { } open func toModels(_ json: JSON, keypath: String? = nil) -> [T]? { - return Array.init(resourceData(from: json, keypath: keypath)) + return [T].init(resourceData(from: json, keypath: keypath)) } } diff --git a/ws/WSNetworkIndicator.swift b/ws/WSNetworkIndicator.swift index 38c20b9..8f8757c 100644 --- a/ws/WSNetworkIndicator.swift +++ b/ws/WSNetworkIndicator.swift @@ -10,7 +10,7 @@ import Foundation /** Abstracts network activity indicator management. - - This only shows activity indicator for requests longer than 1 second, so that loader is not shown for quick requests. + - This only shows activity indicator for requests longer than 1 second, the loader is not shown for quick requests. - This also waits for 0.2 seconds before hiding the indicator in case other simultaneous requests occur in order to avoid flickering. diff --git a/ws/WSRequest.swift b/ws/WSRequest.swift index 68469c9..2faa959 100644 --- a/ws/WSRequest.swift +++ b/ws/WSRequest.swift @@ -6,10 +6,10 @@ // Copyright © 2016 s4cha. All rights reserved. // -import Foundation import Alamofire -import then import Arrow +import Foundation +import then open class WSRequest { @@ -22,22 +22,22 @@ open class WSRequest { open var baseURL = "" open var URL = "" open var httpVerb = WSHTTPVerb.get - open var params = [String:Any]() + open var params = [String: Any]() open var returnsJSON = true open var headers = [String: String]() - open var fullURL:String { return baseURL + URL} - open var timeout:TimeInterval? - open var logLevels:WSLogLevel { + open var fullURL: String { return baseURL + URL } + open var timeout: TimeInterval? + open var logLevels: WSLogLevel { get { return logger.logLevels } set { logger.logLevels = newValue } } open var postParameterEncoding: ParameterEncoding = URLEncoding() open var showsNetworkActivityIndicator = true - open var errorHandler: ((JSON) -> Error?)? = nil + open var errorHandler: ((JSON) -> Error?)? private let logger = WSLogger() - fileprivate var req:DataRequest?//Alamofire.Request? + fileprivate var req: DataRequest?//Alamofire.Request? public init() {} @@ -56,11 +56,13 @@ open class WSRequest { r.timeoutInterval = t } + var request: URLRequest? if httpVerb == .post || httpVerb == .put { - return try! postParameterEncoding.encode(r, with: params) + request = try? postParameterEncoding.encode(r, with: params) } else { - return try! URLEncoding.default.encode(r, with: params) + request = try? URLEncoding.default.encode(r, with: params) } + return request ?? r } /// Returns Promise containing JSON @@ -86,9 +88,11 @@ open class WSRequest { } } - func sendMultipartRequest(_ resolve:@escaping (_ result:(Int, [AnyHashable: Any], JSON))-> Void, reject:@escaping (_ error: Error) -> Void, progress:@escaping (Float) -> Void) { + func sendMultipartRequest(_ resolve: @escaping (_ result: (Int, [AnyHashable: Any], JSON)) -> Void, + reject: @escaping (_ error: Error) -> Void, + progress:@escaping (Float) -> Void) { upload(multipartFormData: { formData in - for (key,value) in self.params { + for (key, value) in self.params { if let int = value as? Int { let str = "\(int)" if let d = str.data(using: String.Encoding.utf8) { @@ -118,7 +122,8 @@ open class WSRequest { logger.logMultipartRequest(self) } - func sendRequest(_ resolve:@escaping (_ result:(Int, [AnyHashable: Any], JSON))-> Void, reject:@escaping (_ error: Error) -> Void) { + func sendRequest(_ resolve:@escaping (_ result: (Int, [AnyHashable: Any], JSON)) -> Void, + reject: @escaping (_ error: Error) -> Void) { self.req = request(self.buildRequest()) logger.logRequest(self.req!) let bgQueue = DispatchQueue.global(qos:DispatchQoS.QoSClass.default) @@ -126,14 +131,16 @@ open class WSRequest { WSNetworkIndicator.shared.stopRequest() self.logger.logResponse(response) if response.error == nil { - resolve((response.response?.statusCode ?? 0, response.response?.allHeaderFields ?? [:], JSON(1 as AnyObject)!)) + resolve((response.response?.statusCode ?? 0, + response.response?.allHeaderFields ?? [:], JSON(1 as AnyObject)!)) } else { self.rejectCallWithMatchingError(response.response, data: response.data, reject: reject) } } } - func sendJSONRequest(_ resolve:@escaping (_ result:(Int, [AnyHashable: Any], JSON))-> Void, reject:@escaping (_ error: Error) -> Void) { + func sendJSONRequest(_ resolve: @escaping (_ result: (Int, [AnyHashable: Any], JSON)) -> Void, + reject: @escaping (_ error: Error) -> Void) { self.req = request(self.buildRequest()) logger.logRequest(self.req!) let bgQueue = DispatchQueue.global(qos: DispatchQoS.QoSClass.default) @@ -142,7 +149,9 @@ open class WSRequest { } } - func handleJSONResponse(_ response:DataResponse, resolve:(_ result:(Int, [AnyHashable: Any], JSON))-> Void, reject:(_ error: Error) -> Void) { + func handleJSONResponse(_ response: DataResponse, + resolve: (_ result: (Int, [AnyHashable: Any], JSON)) -> Void, + reject: (_ error: Error) -> Void) { WSNetworkIndicator.shared.stopRequest() logger.logResponse(response) switch response.result { @@ -161,22 +170,29 @@ open class WSRequest { } } - func rejectCallWithMatchingError(_ response:HTTPURLResponse?, data:Data? = nil, reject:(_ error: Error) -> Void) { + func rejectCallWithMatchingError(_ response: HTTPURLResponse?, + data: Data? = nil, + reject: (_ error: Error) -> Void) { var error = WSError(httpStatusCode: response?.statusCode ?? 0) if let d = data, - let json = try? JSONSerialization.jsonObject(with: d, options: JSONSerialization.ReadingOptions.allowFragments), + let json = try? JSONSerialization.jsonObject(with: d, + options: JSONSerialization.ReadingOptions.allowFragments), let j = JSON(json as AnyObject?) { error.jsonPayload = j } reject(error as Error) } - func methodForHTTPVerb(_ verb:WSHTTPVerb) -> HTTPMethod { + func methodForHTTPVerb(_ verb: WSHTTPVerb) -> HTTPMethod { switch verb { - case .get : return .get - case .post : return .post - case .put : return .put - case .delete : return .delete + case .get: + return .get + case .post: + return .post + case .put: + return .put + case .delete: + return .delete } } } diff --git a/wsTests/Mapping.swift b/wsTests/Mapping.swift index a081ad4..352bfb5 100644 --- a/wsTests/Mapping.swift +++ b/wsTests/Mapping.swift @@ -15,9 +15,7 @@ extension User:ArrowParsable { email <-- json["email"] name <-- json["name"] phone <-- json["phone"] - var urlString = "" - urlString <-- json["website"] - website = NSURL(string: urlString) // TODO simplify? + website <-- json["website"] company <-- json["company"] address <-- json["address"] diff --git a/wsTests/mappingTests.swift b/wsTests/mappingTests.swift index 36bfb0c..3e5cf62 100644 --- a/wsTests/mappingTests.swift +++ b/wsTests/mappingTests.swift @@ -6,10 +6,10 @@ // Copyright © 2016 s4cha. All rights reserved. // -import XCTest -@testable import ws -import then import Arrow +import then +@testable import ws +import XCTest struct Article { var id: Int = 0 @@ -52,8 +52,7 @@ extension FooBar: ArrowInitializable {} } */ - -class mappingTests: XCTestCase { +class MappingTests: XCTestCase { var ws: WS! diff --git a/wsTests/wsTests.swift b/wsTests/wsTests.swift index 89f073f..fe9beb4 100644 --- a/wsTests/wsTests.swift +++ b/wsTests/wsTests.swift @@ -6,11 +6,11 @@ // Copyright © 2015 s4cha. All rights reserved. // -import XCTest -@testable import ws -import then -import Arrow import Alamofire +import Arrow +import then +@testable import ws +import XCTest // MARK: - Models @@ -20,8 +20,8 @@ struct User { var email = "" var name = "" var phone = "" - var website:NSURL? - var company = Company() // TODO test optinals and forced + var website: NSURL? + var company = Company() var address = Address() } @@ -48,9 +48,9 @@ struct Geo { // MARK: - Usage -class wsTests: XCTestCase { +class WSTests: XCTestCase { - var ws:WS! + var ws: WS! override func setUp() { super.setUp() @@ -65,7 +65,7 @@ class wsTests: XCTestCase { let exp = expectation(description: "") // use "call" to get back a json - ws.get("/users").then { (json:JSON) in + ws.get("/users").then { (_: JSON) in exp.fulfill() } waitForExpectations(timeout: 10, handler: nil) @@ -87,7 +87,7 @@ class wsTests: XCTestCase { func testResponse() { let exp = expectation(description: "") - ws.getRequest("/users").fetch().then { (statusCode, responseHeaders, json) in + ws.getRequest("/users").fetch().then { (statusCode, _, _) in XCTAssertEqual(statusCode, 200) exp.fulfill() } @@ -105,9 +105,9 @@ class wsTests: XCTestCase { let img = UIImage(contentsOfFile: imgPath!) let data = UIImageJPEGRepresentation(img!, 1.0)! - wsFileIO.postMultipart("", name: "file", data: data, fileName: "file", mimeType: "image/jpeg").then { json in + wsFileIO.postMultipart("", name: "file", data: data, fileName: "file", mimeType: "image/jpeg").then { _ in exp.fulfill() - }.onError { error in + }.onError { _ in XCTFail() } waitForExpectations(timeout: 10, handler: nil)