Skip to content

Instantly share code, notes, and snippets.

@shishirthedev
Last active January 17, 2019 11:03
Show Gist options
  • Select an option

  • Save shishirthedev/9558c8206bd0e9e10ff870da60dc7c81 to your computer and use it in GitHub Desktop.

Select an option

Save shishirthedev/9558c8206bd0e9e10ff870da60dc7c81 to your computer and use it in GitHub Desktop.
import UIKit
import Foundation
internal let ACCEPT_HEADER_KEY: String = "Accept"
internal let ACCEPT_HEADER_VALUE: String = "application/json"
class NetworkController {
private init() {}
static let sharedInstance = NetworkController()
func dataRequest<T: Decodable>( url: String,
objectType: T.Type,
method: RequestMethod? = .GET,
parameters: [String : Any]? = nil,
completion: @escaping (Result<T>) -> Void ) {
var request: URLRequest!
if !Reachability.connectedToNetwork{
completion(Result.failure(APPError.connectivityError))
return
}
/*------------------------------------------
POST REQUEST
--------------------------------------------*/
if method == .POST{
guard let urlToRequest = URL(string: url) else { return }
request = URLRequest(url: urlToRequest)
if parameters != nil {
guard let postData = try? JSONSerialization.data(withJSONObject: parameters!, options:[]) else { return }
request.httpBody = postData
}
request.httpMethod = "POST"
}
/*------------------------------------------
GET REQUEST
--------------------------------------------*/
if method == .GET{
var components = URLComponents(string: url)!
if parameters != nil{
var items:[URLQueryItem] = [URLQueryItem]()
for (key,value) in parameters! {
items.append(URLQueryItem(name: key, value: "\(value)"))
}
components.queryItems = items
}
components.percentEncodedQuery = components.percentEncodedQuery?.replacingOccurrences(of: "+", with: "%2B")
guard let urlToRequest = components.url else { return }
request = URLRequest(url: urlToRequest)
request.httpMethod = "GET"
}
request.addValue(ACCEPT_HEADER_VALUE, forHTTPHeaderField: ACCEPT_HEADER_KEY)
request.cachePolicy = .reloadIgnoringLocalAndRemoteCacheData
request.timeoutInterval = 60
let task = URLSession.shared.dataTask(with: request, completionHandler: { data, response, error in
guard error == nil else {
completion(Result.failure(APPError.networkError(error!)))
return
}
guard let jsonData = data else {
completion(Result.failure(APPError.dataNotFound))
return
}
do {
let decodedObject = try JSONDecoder().decode(objectType.self, from: jsonData)
completion(Result.success(decodedObject))
} catch let error {
completion(Result.failure(APPError.jsonParsingError(error as! DecodingError)))
}
})
task.resume()
}
}
enum APPError: Error {
case connectivityError
case networkError(Error)
case dataNotFound
case jsonParsingError(Error)
case invalidStatusCode(Int)
}
enum Result<T> {
case success(T)
case failure(APPError)
}
enum RequestMethod {
case POST
case GET
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment