forked from ghostery/user-agent-ios
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNetworkUtils.swift
65 lines (58 loc) · 1.98 KB
/
NetworkUtils.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
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Network
import SwiftyJSON
public func makeURLSession(userAgent: String, configuration: URLSessionConfiguration, timeout: TimeInterval? = nil) -> URLSession {
configuration.httpAdditionalHeaders = ["User-Agent": userAgent]
if let t = timeout {
configuration.timeoutIntervalForRequest = t
}
return URLSession(configuration: configuration, delegate: nil, delegateQueue: .main)
}
// Used to help replace Alamofire's response.validate()
public func validatedHTTPResponse(_ response: URLResponse?, contentType: String? = nil, statusCode: Range<Int>? = nil) -> HTTPURLResponse? {
if let response = response as? HTTPURLResponse {
if let range = statusCode {
return range.contains(response.statusCode) ? response : nil
}
if let type = contentType {
if let responseType = response.allHeaderFields["Content-Type"] as? String {
return responseType.contains(type) ? response : nil
}
return nil
}
return response
}
return nil
}
public enum HTTPMethod: String {
case options = "OPTIONS"
case get = "GET"
case head = "HEAD"
case post = "POST"
case put = "PUT"
case patch = "PATCH"
case delete = "DELETE"
case trace = "TRACE"
case connect = "CONNECT"
}
public enum JSONSerializeError: Error {
case noData
case parseError
}
public func jsonResponse(fromData data: Data?) throws -> JSON {
guard let data = data, !data.isEmpty else {
throw JSONSerializeError.noData
}
do {
let json = try JSON(data: data)
if json.isError() {
throw JSONSerializeError.parseError
}
return json
} catch {
throw(JSONSerializeError.parseError)
}
}