-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathLyftAPIURLEncoding.swift
More file actions
36 lines (31 loc) · 1.36 KB
/
Copy pathLyftAPIURLEncoding.swift
File metadata and controls
36 lines (31 loc) · 1.36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import Foundation
private func components(forKey key: String, value: Any) -> [URLQueryItem] {
switch value {
case let array as [Any]:
return array.map { URLQueryItem(name: key, value: String(describing: $0)) }
default:
return [URLQueryItem(name: key, value: String(describing: value))]
}
}
/// Encodes given parameters on the request URL by URL-encoding the values and keys. Arrays are supported in
/// the form of `foo=bar&foo=baz`.
///
/// - parameter request: The request to have parameters applied.
/// - parameter parameters: The parameters to apply.
///
/// - returns: A tuple containing the constructed request and the error that occurred during parameter
/// encoding, if any.
func lyftURLEncodedInURL(request: URLRequest, parameters: [String: Any]?) -> (URLRequest, NSError?) {
guard let parameters = parameters else {
return (request, nil)
}
var mutableURLRequest = request
let queryItems = parameters
.sorted { $0.0 < $1.0 }
.flatMap { components(forKey: $0, value: $1) }
var urlComponents = URLComponents(url: mutableURLRequest.url!, resolvingAgainstBaseURL: false)
var localVariable = urlComponents
urlComponents?.queryItems = (localVariable?.queryItems ?? []) + queryItems
mutableURLRequest.url = urlComponents?.url
return (mutableURLRequest, nil)
}