Skip to content

Commit

Permalink
Adds json param encoding option via parameterEncoding enum
Browse files Browse the repository at this point in the history
  • Loading branch information
s4cha committed Aug 25, 2020
1 parent 79b7617 commit f9c2423
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 1 deletion.
1 change: 1 addition & 0 deletions Sources/Networking/Calls/NetworkingClient+Requests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ public extension NetworkingClient {
req.httpVerb = httpVerb
req.route = route
req.params = params
req.parameterEncoding = parameterEncoding
return req
}
}
1 change: 1 addition & 0 deletions Sources/Networking/NetworkingClient.swift
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ public struct NetworkingClient {
public var defaultCollectionParsingKeyPath: String?
let baseURL: String
public var headers = [String: String]()
public var parameterEncoding = ParameterEncoding.urlEncoded

/**
Prints network calls to the console.
Expand Down
20 changes: 19 additions & 1 deletion Sources/Networking/NetworkingRequest.swift
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import Combine

public class NetworkingRequest: NSObject {

var parameterEncoding = ParameterEncoding.urlEncoded
var baseURL = ""
var route = ""
var httpVerb = HTTPVerb.get
Expand Down Expand Up @@ -131,7 +132,12 @@ public class NetworkingRequest: NSObject {
var request = URLRequest(url: url)

if httpVerb != .get && multipartData == nil {
switch parameterEncoding {
case .urlEncoded:
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
case .json:
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
}
}

request.httpMethod = httpVerb.rawValue
Expand All @@ -144,7 +150,14 @@ public class NetworkingRequest: NSObject {
}

if httpVerb != .get && multipartData == nil {
request.httpBody = percentEncodedString().data(using: .utf8)
switch parameterEncoding {
case .urlEncoded:
request.httpBody = percentEncodedString().data(using: .utf8)
case .json:
let jsonData = try? JSONSerialization.data(withJSONObject: params)
print(jsonData)
request.httpBody = jsonData
}
}

// Multipart
Expand Down Expand Up @@ -211,3 +224,8 @@ extension NetworkingRequest: URLSessionTaskDelegate {
progressPublisher.send(progress)
}
}

public enum ParameterEncoding {
case urlEncoded
case json
}

0 comments on commit f9c2423

Please sign in to comment.