-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJSONEncoding.swift
More file actions
42 lines (30 loc) · 1.32 KB
/
JSONEncoding.swift
File metadata and controls
42 lines (30 loc) · 1.32 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
//
// JSONEncoding.swift
// QuickHatch
//
// Created by Daniel Koster on 8/16/19.
// Copyright © 2019 DaVinci Labs. All rights reserved.
//
import Foundation
public struct JSONEncoding: ParameterEncoding {
public static var `default`: JSONEncoding { return JSONEncoding() }
public static var prettyPrinted: JSONEncoding { return JSONEncoding(options: .prettyPrinted) }
public let options: JSONSerialization.WritingOptions
public init(options: JSONSerialization.WritingOptions = []) {
self.options = options
}
public func encode(_ urlRequest: URLRequestProtocol, with parameters: Parameters?) throws -> URLRequest {
var urlRequest = try urlRequest.asURLRequest()
guard let parameters = parameters else { return urlRequest }
do {
let data = try JSONSerialization.data(withJSONObject: parameters, options: options)
if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil {
urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
}
urlRequest.httpBody = data
} catch {
throw EncodingError.parameterEncodingFailed(reason: .jsonEncodingFailed(error: error))
}
return urlRequest
}
}