-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathHttpRequest.swift
78 lines (71 loc) · 2.18 KB
/
HttpRequest.swift
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
// Mezhevikin Alexey: https://github.com/mezhevikin/http-request
import Foundation
public func HttpRequest(
url: String,
method: HttpMethod = .get,
parameters: [String: Any] = [:],
headers: [String: String] = [:]
) -> URLRequest {
let url = method == .get && !parameters.isEmpty ?
url + "?" + parameters.query : url
var request = URLRequest(url: URL(string: url)!)
request.httpMethod = "\(method)".uppercased()
request.allHTTPHeaderFields = headers
if method == .post && !parameters.isEmpty {
request.httpBody = parameters.query.data(using: .utf8)
}
return request
}
public enum HttpMethod: String {
case get, post, head, put, delete
}
public extension URLRequest {
func data(completion: @escaping ((HttpResponse) -> Void)) {
URLSession.shared.dataTask(with: self) { data, original, error in
let response = HttpResponse()
response.original = original as? HTTPURLResponse
response.data = data
response.error = error
completion(response)
}.resume()
}
func json<T>(
_ type: T.Type,
completion: @escaping ((T?, HttpResponse) -> Void)
) -> Void where T : Decodable {
data { response in
var json: T? = nil
if let data = response.data {
do {
json = try JSONDecoder().decode(T.self, from: data)
} catch {
response.error = error
}
}
DispatchQueue.main.async {
completion(json, response)
}
}
}
}
public class HttpResponse {
public var original: HTTPURLResponse?
public var data: Data?
public var error: Error?
public var success: Bool {
guard let original else { return false }
return 200 ..< 300 ~= original.statusCode
}
}
extension Dictionary {
var query: String {
map() { key, value -> String in
"\(key)=\("\(value)".urlEncoded)"
}.joined(separator: "&")
}
}
extension String {
var urlEncoded: String {
addingPercentEncoding(withAllowedCharacters: CharacterSet.alphanumerics)!
}
}