Skip to content

Instantly share code, notes, and snippets.

@khanlou
Created March 25, 2018 19:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save khanlou/b6b3818f7ca7160a9d88ececdd7a34f8 to your computer and use it in GitHub Desktop.
Save khanlou/b6b3818f7ca7160a9d88ececdd7a34f8 to your computer and use it in GitHub Desktop.
enum SharedNetworkClient {
static let googleMaps: NetworkClient = {
let keyBehavior = AddQueryItemsBehavior(name: "key", value: "$YR_KEY")
let configuration = RequestConfiguration(baseURLString: "https://maps.googleapis.com/", defaultRequestBehavior: keyBehavior)
let client = NetworkClient(configuration: configuration)
return client
}()
}
struct AddQueryItemsBehavior: RequestBehavior {
let queryItems: [URLQueryItem]
init(queryItems: [URLQueryItem]) {
self.queryItems = queryItems
}
init(name: String, value: String?) {
self.init(queryItems: [URLQueryItem(name: name, value: value)])
}
func modify(request: URLRequest) -> URLRequest {
var copy = request
guard let url = copy.url else { fatalError() }
guard var urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false) else { fatalError() }
urlComponents.queryItems = (urlComponents.queryItems ?? []) + queryItems
guard let newURL = urlComponents.url else { fatalError() }
copy.url = newURL
return copy
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment