Skip to content

Commit

Permalink
default header value added for content type, if not specified
Browse files Browse the repository at this point in the history
  • Loading branch information
Ayush Awasthi committed Jan 30, 2019
1 parent dffeedb commit 235d567
Showing 1 changed file with 18 additions and 4 deletions.
22 changes: 18 additions & 4 deletions KiwiPods/Networking/NetworkModel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,9 @@ public enum RequestType: String {
case POST,
GET,
DELETE,
PUT
PUT,
HEAD

public var httpMethod: HTTPMethod {
switch self {
case .POST:
Expand Down Expand Up @@ -43,7 +45,8 @@ public protocol APIConfigurable: URLRequestConvertible {
public extension APIConfigurable {
public func asURLRequest() throws -> URLRequest {
var queryItems = ""
if type == .GET, parameters.count > 0 {
let hasUrlEncodedParams = (type == .GET || type == .DELETE || type == .HEAD)
if hasUrlEncodedParams, parameters.count > 0 {
queryItems = parameters.reduce("?") { (value: String, arg1: (String, Any)) -> String in
return value + "\(arg1.0)=\(arg1.1)&"
}
Expand All @@ -52,8 +55,19 @@ public extension APIConfigurable {
let url = URL(string: (path + queryItems))
do {
var urlRequest = try URLRequest(url: url!, method: type.httpMethod)
urlRequest.allHTTPHeaderFields = headers
if type != .GET {
var apiHeaders = self.headers
//check if `Content-Type` is provided
// if `Content-Type` are not provided then add `application/json` as default
if let headers = apiHeaders {
if headers["Content-Type"] == nil {
apiHeaders?["Content-Type"] = "application/json"
}
} else {
apiHeaders = [:]
apiHeaders?["Content-Type"] = "application/json"
}
urlRequest.allHTTPHeaderFields = apiHeaders
if !hasUrlEncodedParams {
urlRequest.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: JSONSerialization.WritingOptions.prettyPrinted)
}
return urlRequest
Expand Down

0 comments on commit 235d567

Please sign in to comment.