Skip to content

Instantly share code, notes, and snippets.

@ARamy23
Last active June 12, 2018 14:24
Show Gist options
  • Save ARamy23/bdcad3bdc002ccbfade54add3336125b to your computer and use it in GitHub Desktop.
Save ARamy23/bdcad3bdc002ccbfade54add3336125b to your computer and use it in GitHub Desktop.
a generic network call function
func getData<T: Codable>(endpoint: String, method: HTTPMethod?, params: [String: Any]?, headers: [String: String]?, model: T.Type, completion: @escaping (T?, URLResponse?, Error?) -> Void)
{
//1
guard let url = URL(string: Constants.mainURLString.rawValue + endpoint) else {print("error with creating url"); return;}
var request = URLRequest(url: url)
//2
request.httpMethod = method?.rawValue ?? "GET"
//3
if let headers = headers
{
for (key, value) in headers
{
request.addValue(value, forHTTPHeaderField: key)
}
}
//4
if let parameters = params
{
do
{
request.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted)
}
catch let error
{
completion(nil, nil, error)
return
}
}
//5
URLSession.shared.dataTask(with: request) { (data, response, error) in
//6
if error != nil
{
completion(nil, nil, error)
return
}
//7
do
{
let jsonData = try JSONDecoder().decode(model, from: data!)
completion(jsonData, response, nil)
}
catch let error
{
completion(nil, nil, error)
}
}.resume()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment