Skip to content

Instantly share code, notes, and snippets.

@chaitanyaSoni96
Created June 21, 2020 12:03
Show Gist options
  • Save chaitanyaSoni96/b1b9e77bf1565e3b1411bc90156e66ab to your computer and use it in GitHub Desktop.
Save chaitanyaSoni96/b1b9e77bf1565e3b1411bc90156e66ab to your computer and use it in GitHub Desktop.
URLSession class for generic api calls in swift
//
// PEAPIUtilityExt.swift
// ProcializeEvents
//
// Created by Chaitanya Soni on 21/06/20.
// Copyright © 2020 Chaitanya Soni. All rights reserved.
//
import Foundation
public typealias JSON = [String: Any]
public typealias HTTPHeaders = [String: String]
public enum RequestMethod: String {
case get = "GET"
case post = "POST"
case put = "PUT"
case delete = "DELETE"
}
public class APIClient {
static let shared = APIClient()
public func sendRequest<T: Decodable>(for: T.Type = T.self,
url: String,
method: RequestMethod,
headers: HTTPHeaders? = nil,
body: JSON? = nil,
completion: @escaping (Result<T>) -> Void) {
return sendRequest(url: url, method: method, headers: headers, body:body, completion: completion) { decoder, data in try decoder.decode(T.self, from: data) }
}
public func sendRequest<T: Decodable>(for: [T].Type = [T].self,
url: String,
method: RequestMethod,
headers: HTTPHeaders? = nil,
body: JSON? = nil,
completion: @escaping (Result<[T]>) -> Void) {
return sendRequest(url: url, method: method, headers: headers, body:body, completion: completion) { decoder, data in try decoder.decode([T].self, from: data) }
}
private func sendRequest(_ url: String,
method: RequestMethod,
headers: HTTPHeaders? = nil,
body: JSON? = nil,
completionHandler: @escaping (Data?, URLResponse?, Error?) -> Void) {
let url = URL(string: url)!
var urlRequest = URLRequest(url: url)
urlRequest.httpMethod = method.rawValue
if let headers = headers {
urlRequest.allHTTPHeaderFields = headers
urlRequest.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
}
if let body = body {
urlRequest.httpBody = try? JSONSerialization.data(withJSONObject: body)
}
let session = URLSession(configuration: .default)
let task = session.dataTask(with: urlRequest) { data, response, error in
completionHandler(data, response, error)
}
task.resume()
}
private func sendRequest<T>(url: String,
method: RequestMethod,
headers: HTTPHeaders? = nil,
body: JSON? = nil,
completion: @escaping (Result<T>) -> Void,
decodingWith decode: @escaping (JSONDecoder, Data) throws -> T) {
return sendRequest(url, method: method, headers: headers, body:body) { data, response, error in
guard let data = data else {
return completion(.failure((error ?? NSError(domain: "SomeDomain", code: -1, userInfo: nil)) as NSError))
}
do {
let decoder = JSONDecoder()
// asking the custom decoding block to do the work
try completion(.success(decode(decoder, data)))
} catch let decodingError {
completion(.failure(decodingError as NSError))
}
}
}
}
@theabhieye
Copy link

theabhieye commented Sep 8, 2022

`

private func sendRequest(_ url: String,
method: RequestMethod,
headers: HTTPHeaders? = nil,
body: JSON? = nil,
completionHandler: @escaping (Data?, URLResponse?, Error?) -> Void) {

	guard let formatedURL = url.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed),
		  let url = URL(string: formatedURL) else {
		return
	}

	var urlRequest = URLRequest(url: url)
	urlRequest.httpMethod = method.rawValue
	
	if let headers = headers {
		urlRequest.allHTTPHeaderFields = headers
		urlRequest.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
	}
	
	if let body = body {
		urlRequest.httpBody = try? JSONSerialization.data(withJSONObject: body)
	}
	
	let session = URLSession(configuration: .default)
	let task = session.dataTask(with: urlRequest) { data, response, error in
		completionHandler(data, response, error)
	}
	
	task.resume()
}

`

For allowing whitespaces in get request

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment