Skip to content
This repository has been archived by the owner on Oct 29, 2021. It is now read-only.

Commit

Permalink
Merge pull request #13 from intelygenz/feature/acceptable-status-codes
Browse files Browse the repository at this point in the history
Added customizable acceptable status codes range.
  • Loading branch information
alexruperez authored Mar 6, 2018
2 parents c8c0f91 + 93d16c6 commit b46c0fc
Show file tree
Hide file tree
Showing 14 changed files with 57 additions and 28 deletions.
3 changes: 2 additions & 1 deletion Alamofire/NetAlamofire+Data.swift
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,8 @@ extension NetAlamofire {
netDataTask?.progress = progress
netDataTask?.progressClosure?(progress)
}
dataRequest.response(queue: queue) { [weak self] response in
.validate(statusCode: acceptableStatusCodes)
.response(queue: queue) { [weak self] response in
let netResponse = self?.netResponse(response.response, netDataTask, response.data)
let netError = self?.netError(response.error, response.data, response.response)
netDataTask?.response = netResponse
Expand Down
6 changes: 4 additions & 2 deletions Alamofire/NetAlamofire+Download.swift
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,8 @@ extension NetAlamofire {
netDownloadTask?.progress = progress
netDownloadTask?.progressClosure?(progress)
}
downloadRequest.response(queue: queue) { [weak self] response in
.validate(statusCode: acceptableStatusCodes)
.response(queue: queue) { [weak self] response in
let netResponse = self?.netResponse(response.response, netDownloadTask, response.destinationURL)
let netError = self?.netError(response.error, response.destinationURL, response.response)
netDownloadTask?.response = netResponse
Expand All @@ -43,7 +44,8 @@ extension NetAlamofire {
netDownloadTask?.progress = progress
netDownloadTask?.progressClosure?(progress)
}
downloadRequest.response(queue: queue) { [weak self] response in
.validate(statusCode: acceptableStatusCodes)
.response(queue: queue) { [weak self] response in
let netResponse = self?.netResponse(response.response, netDownloadTask, response.destinationURL)
let netError = self?.netError(response.error, response.destinationURL, response.response)
netDownloadTask?.response = netResponse
Expand Down
9 changes: 6 additions & 3 deletions Alamofire/NetAlamofire+Upload.swift
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,8 @@ extension NetAlamofire {
netUploadTask?.progress = progress
netUploadTask?.progressClosure?(progress)
}
uploadRequest.response(queue: queue) { [weak self] response in
.validate(statusCode: acceptableStatusCodes)
.response(queue: queue) { [weak self] response in
let netResponse = self?.netResponse(response.response, netUploadTask, response.data)
let netError = self?.netError(response.error, response.data, response.response)
netUploadTask?.response = netResponse
Expand Down Expand Up @@ -61,7 +62,8 @@ extension NetAlamofire {
netUploadTask?.progress = progress
netUploadTask?.progressClosure?(progress)
}
uploadRequest.response(queue: queue) { [weak self] response in
.validate(statusCode: acceptableStatusCodes)
.response(queue: queue) { [weak self] response in
let netResponse = self?.netResponse(response.response, netUploadTask, response.data)
let netError = self?.netError(response.error, response.data, response.response)
netUploadTask?.response = netResponse
Expand Down Expand Up @@ -104,7 +106,8 @@ extension NetAlamofire {
netUploadTask?.progress = progress
netUploadTask?.progressClosure?(progress)
}
uploadRequest.response(queue: queue) { [weak self] response in
.validate(statusCode: acceptableStatusCodes)
.response(queue: queue) { [weak self] response in
let netResponse = self?.netResponse(response.response, netUploadTask, response.data)
let netError = self?.netError(response.error, response.data, response.response)
netUploadTask?.response = netResponse
Expand Down
4 changes: 3 additions & 1 deletion Alamofire/NetAlamofire.swift
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,8 @@ open class NetAlamofire: Net {
}
}

open var acceptableStatusCodes = defaultAcceptableStatusCodes

open private(set) var sessionManager: Alamofire.SessionManager!

open var authChallenge: ((URLAuthenticationChallenge, (URLSession.AuthChallengeDisposition, URLCredential?) -> Swift.Void) -> Swift.Void)? {
Expand Down Expand Up @@ -131,7 +133,7 @@ extension NetAlamofire {

func netError(_ error: Error?, _ responseObject: Any? = nil, _ response: URLResponse? = nil) -> NetError? {
if let error = error {
return NetError.net(code: error._code, message: error.localizedDescription, headers: (response as? HTTPURLResponse)?.allHeaderFields, object: responseObject, underlying: error)
return .net(code: error._code, message: error.localizedDescription, headers: (response as? HTTPURLResponse)?.allHeaderFields, object: responseObject, underlying: error)
}
return nil
}
Expand Down
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
# Release 0.4.5

- [x] Added customizable acceptable status codes range

# Release 0.4.4

- [x] [#12](https://github.com/intelygenz/NetClient-iOS/pull/12) New removable interceptors API
Expand Down
10 changes: 10 additions & 0 deletions Core/Net.swift
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,10 @@ import Foundation

public typealias InterceptorToken = UUID

public typealias StatusCode = Int

public typealias StatusCodes = Set<StatusCode>

public typealias RequestInterceptor = (NetRequest.Builder) -> NetRequest.Builder

public typealias ResponseInterceptor = (NetResponse.Builder) -> NetResponse.Builder
Expand All @@ -26,6 +30,8 @@ public protocol Net: class {

@discardableResult func removeInterceptor(_ token: InterceptorToken) -> Bool

var acceptableStatusCodes: StatusCodes { get set }

func data(_ request: NetRequest) -> NetTask

func download(_ resumeData: Data) -> NetTask
Expand All @@ -50,3 +56,7 @@ public protocol Net: class {
#endif

}

extension Net {
static var defaultAcceptableStatusCodes: StatusCodes { return Set(200..<300) }
}
14 changes: 7 additions & 7 deletions Core/NetMultipartFormData.swift
Original file line number Diff line number Diff line change
Expand Up @@ -313,16 +313,16 @@ public class NetMultipartFormData {
}

if FileManager.default.fileExists(atPath: fileURL.path) {
let underlying = URLError(.fileDoesNotExist)
throw NetError.parse(code: underlying._code, message: "Output stream file already exists.", object: fileURL, underlying: underlying)
let urlError = URLError(.fileDoesNotExist)
throw NetError.parse(code: urlError._code, message: "Output stream file already exists.", object: fileURL, underlying: urlError)
} else if !fileURL.isFileURL {
let underlying = URLError(.badURL)
throw NetError.parse(code: underlying._code, message: "Output stream URL is invalid.", object: fileURL, underlying: underlying)
let urlError = URLError(.badURL)
throw NetError.parse(code: urlError._code, message: "Output stream URL is invalid.", object: fileURL, underlying: urlError)
}

guard let outputStream = OutputStream(url: fileURL, append: false) else {
let underlying = URLError(.cannotCreateFile)
throw NetError.parse(code: underlying._code, message: "Output stream creation failed.", object: fileURL, underlying: underlying)
let urlError = URLError(.cannotCreateFile)
throw NetError.parse(code: urlError._code, message: "Output stream creation failed.", object: fileURL, underlying: urlError)
}

outputStream.open()
Expand Down Expand Up @@ -502,7 +502,7 @@ public class NetMultipartFormData {
guard bodyPartError == nil else {
return
}
bodyPartError = NetError.parse(code: underlying?._code, message: reason, object: object, underlying: underlying)
bodyPartError = .parse(code: underlying?._code, message: reason, object: object, underlying: underlying)
}


Expand Down
10 changes: 5 additions & 5 deletions Core/NetTask.swift
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ open class NetTask: NetTaskProtocol,
let dispatchTimeoutResult = dispatchSemaphore?.wait(timeout: DispatchTime.distantFuture)
if dispatchTimeoutResult == .timedOut {
let urlError = URLError(.timedOut)
error = NetError.net(code: urlError._code, message: urlError.localizedDescription, headers: response?.headers, object: response?.responseObject, underlying: urlError)
error = .net(code: urlError._code, message: urlError.localizedDescription, headers: response?.headers, object: response?.responseObject, underlying: urlError)
}
if let error = error {
throw error
Expand All @@ -139,17 +139,17 @@ open class NetTask: NetTaskProtocol,
}
guard let urlRequest = request?.urlRequest else {
guard let taskError = error else {
let error = URLError(.resourceUnavailable)
throw NetError.net(code: error._code, message: "Request not found.", headers: response?.headers, object: response?.responseObject, underlying: error)
let urlError = URLError(.resourceUnavailable)
throw NetError.net(code: urlError._code, message: "Request not found.", headers: response?.headers, object: response?.responseObject, underlying: urlError)
}
throw taskError
}
if let cachedResponse = URLCache.shared.cachedResponse(for: urlRequest) {
return NetResponse(cachedResponse, self)
}
guard let taskError = error else {
let error = URLError(.resourceUnavailable)
throw NetError.net(code: error._code, message: "Cached response not found.", headers: response?.headers, object: response?.responseObject, underlying: error)
let urlError = URLError(.resourceUnavailable)
throw NetError.net(code: urlError._code, message: "Cached response not found.", headers: response?.headers, object: response?.responseObject, underlying: urlError)
}
throw taskError
}
Expand Down
6 changes: 3 additions & 3 deletions Example/ViewController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -72,12 +72,12 @@ class ViewController: UIViewController {
// Decode
net.data(request).async { (response, error) in
do {
if let article: Article = try response?.decode() {
if let error = error {
print("Net error: \(error)")
} else if let article: Article = try response?.decode() {
print(article)
// Encode
try request.builder().setJSONObject(article)
} else if let error = error {
print("Net error: \(error)")
}
} catch {
print("Parse error: \(error.localizedDescription)")
Expand Down
8 changes: 4 additions & 4 deletions Net.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -1566,8 +1566,8 @@
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
CURRENT_PROJECT_VERSION = "$(DYLIB_CURRENT_VERSION)";
DEVELOPMENT_TEAM = 3VW789WSMP;
DYLIB_COMPATIBILITY_VERSION = 0.4.0;
DYLIB_CURRENT_VERSION = 0.4.4;
DYLIB_COMPATIBILITY_VERSION = 0.4.5;
DYLIB_CURRENT_VERSION = 0.4.5;
ENABLE_STRICT_OBJC_MSGSEND = YES;
ENABLE_TESTABILITY = YES;
GCC_C_LANGUAGE_STANDARD = gnu99;
Expand Down Expand Up @@ -1620,8 +1620,8 @@
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
CURRENT_PROJECT_VERSION = "$(DYLIB_CURRENT_VERSION)";
DEVELOPMENT_TEAM = 3VW789WSMP;
DYLIB_COMPATIBILITY_VERSION = 0.4.0;
DYLIB_CURRENT_VERSION = 0.4.4;
DYLIB_COMPATIBILITY_VERSION = 0.4.5;
DYLIB_CURRENT_VERSION = 0.4.5;
ENABLE_STRICT_OBJC_MSGSEND = YES;
GCC_C_LANGUAGE_STANDARD = gnu99;
GCC_NO_COMMON_BLOCKS = YES;
Expand Down
2 changes: 1 addition & 1 deletion NetClient.podspec
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
Pod::Spec.new do |s|
s.name = 'NetClient'
s.version = '0.4.4'
s.version = '0.4.5'
s.summary = 'Versatile HTTP networking library written in Swift.'

s.homepage = 'https://github.com/intelygenz/NetClient-iOS'
Expand Down
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
- [x] TLS Certificate and Public Key Pinning
- [x] Retry requests
- [x] Codable / Decodable / Encodable protocols compatible (JSON / Property List)
- [x] Customizable acceptable status codes range
- [x] watchOS Compatible
- [x] tvOS Compatible
- [x] macOS Compatible
Expand Down
2 changes: 2 additions & 0 deletions Stub/NetStub.swift
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ open class NetStub: Net {

open var retryClosure: NetTask.RetryClosure?

open var acceptableStatusCodes = defaultAcceptableStatusCodes

open var nextResult: Result?

public init(_ nextResult: Result? = nil) {
Expand Down
6 changes: 5 additions & 1 deletion URLSession/NetURLSession.swift
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,8 @@ open class NetURLSession: Net {

open var retryClosure: NetTask.RetryClosure?

open var acceptableStatusCodes = defaultAcceptableStatusCodes

open private(set) var authChallenge: ((URLAuthenticationChallenge, (URLSession.AuthChallengeDisposition, URLCredential?) -> Swift.Void) -> Swift.Void)?

open private(set) var serverTrust = [String: NetServerTrust]()
Expand Down Expand Up @@ -158,7 +160,9 @@ extension NetURLSession {

func netError(_ error: Error?, _ responseObject: Any? = nil, _ response: URLResponse? = nil) -> NetError? {
if let error = error {
return NetError.net(code: error._code, message: error.localizedDescription, headers: (response as? HTTPURLResponse)?.allHeaderFields, object: responseObject, underlying: error)
return .net(code: error._code, message: error.localizedDescription, headers: (response as? HTTPURLResponse)?.allHeaderFields, object: responseObject, underlying: error)
} else if let httpResponse = response as? HTTPURLResponse, !acceptableStatusCodes.contains(httpResponse.statusCode) {
return .net(code: httpResponse.statusCode, message: HTTPURLResponse.localizedString(forStatusCode: httpResponse.statusCode), headers: httpResponse.allHeaderFields, object: responseObject, underlying: error)
}
return nil
}
Expand Down

0 comments on commit b46c0fc

Please sign in to comment.