Created
January 10, 2019 09:15
-
-
Save kphetrungnapha/3d1dcfce605cbc8b7c28060fbee998bf to your computer and use it in GitHub Desktop.
Revisions
-
Kittisak Phetrungnapha created this gist
Jan 10, 2019 .There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,71 @@ enum Router { case getContacts case getContact(id: Int) case createContact(body: [String: Any]) case updateContact(id: Int, body: [String: Any]) private static let baseURLString = "YOUR_BASE_URL_STRING" private enum HTTPMethod { case get case post case put case delete var value: String { switch self { case .get: return "GET" case .post: return "POST" case .put: return "PUT" case .delete: return "DELETE" } } } private var method: HTTPMethod { switch self { case .getContacts: return .get case .getContact: return .get case .createContact: return .post case .updateContact: return .put } } private var path: String { switch self { case .getContacts: return "/contacts.json" case .getContact(let id): return "/contacts/\(id).json" case .createContact: return "/contacts.json" case .updateContact(let id, _): return "/contacts/\(id).json" } } func request() throws -> URLRequest { let urlString = "\(Router.baseURLString)\(path)" guard let url = URL(string: urlString) else { throw ErrorType.parseUrlFail } var request = URLRequest(url: url, cachePolicy: .reloadIgnoringCacheData, timeoutInterval: 10) request.httpMethod = method.value request.addValue("application/json", forHTTPHeaderField: "Content-Type") switch self { case .getContacts: return request case .getContact: return request case .createContact(let body): request.httpBody = try JSONSerialization.data(withJSONObject: body, options: .prettyPrinted) return request case .updateContact(_, let body): request.httpBody = try JSONSerialization.data(withJSONObject: body, options: .prettyPrinted) return request } } }