Skip to content

Instantly share code, notes, and snippets.

@adamzarn
Last active January 24, 2022 23:22
Show Gist options
  • Save adamzarn/8aa8f5830f25572d0e8d8a0c29d5bcfc to your computer and use it in GitHub Desktop.
Save adamzarn/8aa8f5830f25572d0e8d8a0c29d5bcfc to your computer and use it in GitHub Desktop.
A protocol to make constructing a URLRequest easier
import Foundation
protocol URLRequestConvertible {
var baseUrl: String { get }
var path: String? { get }
var httpMethod: String { get }
var httpBody: Data? { get }
var allHTTPHeaderFields: [String: String] { get }
var url: URL? { get }
var urlRequest: URLRequest? { get }
}
extension URLRequestConvertible {
var url: URL? {
var urlString = baseUrl
urlString += path ?? ""
return URL(string: urlString)
}
var urlRequest: URLRequest? {
guard let url = url else { return nil }
var urlRequest = URLRequest(url: url)
urlRequest.httpMethod = httpMethod
urlRequest.httpBody = httpBody
urlRequest.allHTTPHeaderFields = allHTTPHeaderFields
return urlRequest
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment