Skip to content

Instantly share code, notes, and snippets.

@RinniSwift
Last active April 10, 2024 19:56
Show Gist options
  • Save RinniSwift/c85ccffdc9e837375a7409d6cd510785 to your computer and use it in GitHub Desktop.
Save RinniSwift/c85ccffdc9e837375a7409d6cd510785 to your computer and use it in GitHub Desktop.
class ServiceLayer {
// 1.
class func request<T: Codable>(router: Router, completion: @escaping (Result<[String: [T]], Error>) -> ()) {
// 2.
var components = URLComponents()
components.scheme = router.scheme
components.host = router.host
components.path = router.path
components.queryItems = router.parameters
// 3.
guard let url = components.url else { return }
var urlRequest = URLRequest(url: url)
urlRequest.httpMethod = router.method
// 4.
let session = URLSession(configuration: .default)
let dataTask = session.dataTask(with: urlRequest) { data, response, error in
// 5.
if let err = error {
completion(.failure(err))
print(err.localizedDescription)
return
}
guard response != nil, let data = data else {
return
}
// 6.
let responseObject = try! JSONDecoder().decode([String: [T]].self, from: data)
// 7.
DispatchQueue.main.async {
// 8.
completion(.success(responseObject))
}
}
dataTask.resume()
}
}
@RinniSwift
Copy link
Author

RinniSwift commented Feb 28, 2021

@underthevalley

Hi, I tried this code out and got an error on line 18. Should it be an assignation '=' rather than a comparison '=='

Thanks for catching this, it is supposed to be an assignment! -- gist updated.

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