Created
October 28, 2017 02:26
-
-
Save pedantix/52398fc9b140c785bde9229782e39ec8 to your computer and use it in GitHub Desktop.
Swift 4 Encapsulate the URLRequests
This file contains 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 characters
// I needed to make a gist to show some things off and whats nots | |
import Foundation | |
enum HttpMethod: String { | |
case get = "GET" | |
case post = "POST" | |
case patch = "PATCH" | |
case delete = "DELETE" | |
} | |
struct ReqComps<T: Encodable> { | |
let method: HttpMethod | |
let params: [URLQueryItem] | |
let body: T? | |
let path: String | |
} | |
func makeUrlReq<U>(reqComps: ReqComps<U>) -> URLRequest? { | |
// Obviously dont store your URL string here | |
guard var urlComps = URLComponents(string: "http://www.example.com/\(reqComps.path)") | |
else { return nil } | |
urlComps.queryItems = reqComps.params | |
guard let url = urlComps.url else { return nil } | |
var req = URLRequest(url: url) | |
req.httpMethod = reqComps.method.rawValue | |
if let body = reqComps.body { | |
// Dont Encode With a bang | |
req.httpBody = try! JSONEncoder().encode(body) | |
} | |
// Do other things like add headers here | |
return req | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment