Last active
February 28, 2021 10:07
-
-
Save Roshankumar350/a7a815c4d3a184e7391811d659bde8cc to your computer and use it in GitHub Desktop.
Handy network extension
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
import Combine | |
// MARK: - Error | |
enum APIError: Error, LocalizedError { | |
case unKnown | |
case apiError(reason: String) | |
} | |
extension APIError { | |
var errorDescription: String? { | |
switch self { | |
case .unKnown: | |
return "Unknown Error" | |
case .apiError(reason: let reason): | |
return reason | |
} | |
} | |
} | |
extension URLSession { | |
// MARK: - Behaviour | |
func callingEndPoint(forRequest request: URLRequest) -> AnyPublisher<Data, APIError> { | |
return self.dataTaskPublisher(for: request) | |
.tryMap { data, response in | |
guard let httpResponse = response as? HTTPURLResponse, 200..<300 ~= httpResponse.statusCode else { | |
throw APIError.unKnown | |
} | |
return data | |
} | |
.mapError { error in | |
if let error = error as? APIError { | |
return error | |
} else { | |
return APIError.apiError(reason: error.localizedDescription) | |
} | |
} | |
.eraseToAnyPublisher() | |
} | |
} | |
extension URLRequest { | |
// MARK: - HTTP Methods | |
enum HTTPMethod: String { | |
case GET | |
case POST | |
var httpRawValue: String { | |
switch self { | |
case .GET: | |
return self.rawValue | |
case .POST: | |
return self.rawValue | |
} | |
} | |
} | |
// MARK: - URL | |
enum URLString: String { | |
case recipe = "https://s3-ap-southeast-1.amazonaws.com/he-public-data/reciped9d7b8c.json" | |
var url: URL { | |
switch self { | |
case .recipe: | |
return URL(string: self.rawValue)! | |
} | |
} | |
} | |
// MARK: - Initilalizers | |
init(forHttpMethod httpMethod: HTTPMethod, forAssociatedURL urlString: URLString) { | |
self.init(url: urlString.url) | |
self.httpMethod = httpMethod.httpRawValue | |
} | |
} | |
/* | |
To use this | |
Step 1: Create session | |
lazy var session: URLSession = { | |
let config: URLSessionConfiguration = .default | |
config.waitsForConnectivity = true | |
return URLSession(configuration: config) | |
}() | |
Step 1: Use session to call the api | |
session.callingEndPoint(.... | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment