-
Notifications
You must be signed in to change notification settings - Fork 205
Expand file tree
/
Copy pathFormURLEncodedDataParser.swift
More file actions
43 lines (33 loc) · 1.31 KB
/
FormURLEncodedDataParser.swift
File metadata and controls
43 lines (33 loc) · 1.31 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
37
38
39
40
41
42
43
import Foundation
/// `FormURLEncodedDataParser` parses form URL encoded response data.
public class FormURLEncodedDataParser: DataParser {
public enum Error: Swift.Error {
case cannotGetStringFromData(Data)
}
/// The string encoding of the data.
public let encoding: String.Encoding
/// Returns `FormURLEncodedDataParser` with the string encoding.
public init(encoding: String.Encoding) {
self.encoding = encoding
}
// MARK: - DataParser
/// Value for `Accept` header field of HTTP request.
public var contentType: String? {
return "application/x-www-form-urlencoded"
}
/// Return `[String: Any]` that expresses structure of response.
/// - Throws: `FormURLEncodedDataParser.Error` when the parser fails to initialize `String` from `Data`.
public func parse(data: Data) throws -> [String: Any] {
guard let string = String(data: data, encoding: encoding) else {
throw Error.cannotGetStringFromData(data)
}
var components = URLComponents()
components.percentEncodedQuery = string
let queryItems = components.queryItems ?? []
var dictionary = [String: Any]()
for queryItem in queryItems {
dictionary[queryItem.name] = queryItem.value
}
return dictionary
}
}