From 798164db26134c200e3d1cbc8bb003f4b9f63600 Mon Sep 17 00:00:00 2001 From: Basil Alamoudi Date: Sat, 1 Sep 2018 23:53:24 +0300 Subject: [PATCH] Add files via upload --- .../Extensions/GenericRESTClient.swift | 80 +++++++++++++++++++ 1 file changed, 80 insertions(+) create mode 100644 Helper4Swift/Classes/Extensions/GenericRESTClient.swift diff --git a/Helper4Swift/Classes/Extensions/GenericRESTClient.swift b/Helper4Swift/Classes/Extensions/GenericRESTClient.swift new file mode 100644 index 0000000..9e974c3 --- /dev/null +++ b/Helper4Swift/Classes/Extensions/GenericRESTClient.swift @@ -0,0 +1,80 @@ +// +// ViewController.swift +// GenericsDecodableAndEncodableJSON +// +// Created by X901 on 11/08/2018. +// Copyright © 2018 X901. All rights reserved. +// + +import Foundation + +protocol GenericRESTClient { + func getGenericData(urlString: String, completion: @escaping (T) -> ()) + func postGenericData(urlString: String, parameter: T, completion: @escaping (Data?, URLResponse?, Error?) -> ()) +} + +extension GenericRESTClient { + + func getGenericData(urlString: String, completion: @escaping (T) -> ()) { + + let url = URL(string: urlString) + URLSession.shared.dataTask(with: url!) { (data, response, error) in + if let error = error { + print("Failed to fetch data:", error) + return + } + + + guard let data = data else { return } + + do { + let obj = try JSONDecoder().decode(T.self, from: data) + completion(obj) + } catch let jsonErr { + print("Failed to decode json:", jsonErr) + } + }.resume() + } + + func postGenericData(urlString: String, parameter: T, completion: @escaping (Data?, URLResponse?, Error?) -> ()) { + + let url = URL(string: urlString) + var request = URLRequest(url: url!) + request.httpMethod = "POST" + request.addValue("application/json", forHTTPHeaderField: "Content-Type") + + do { + let jsonBody = try JSONEncoder().encode(parameter) + + request.httpBody = jsonBody + + + + + + } catch let jsonErr { + print("Failed to encode json:", jsonErr) + } + + + let session = URLSession.shared + _ = session.dataTask(with: request) { (data,response, error) in + + + + completion(data,response, error) + + + + + }.resume() + + } + +} + + + + + +