Przeglądaj źródła

Added JSON encoding encode method that takes a JSON object along with unit tests.

Christian Noon 9 lat temu
rodzic
commit
ab07523ee9
2 zmienionych plików z 60 dodań i 2 usunięć
  1. 28 0
      Source/ParameterEncoding.swift
  2. 32 2
      Tests/ParameterEncodingTests.swift

+ 28 - 0
Source/ParameterEncoding.swift

@@ -321,6 +321,34 @@ public struct JSONEncoding: ParameterEncoding {
 
         return urlRequest
     }
+
+    /// Creates a URL request by encoding the JSON object and setting the resulting data on the HTTP body.
+    ///
+    /// - parameter urlRequest: The request to apply the JSON object to.
+    /// - parameter jsonObject: The JSON object to apply to the request.
+    ///
+    /// - throws: An `Error` if the encoding process encounters an error.
+    ///
+    /// - returns: The encoded request.
+    public func encode(_ urlRequest: URLRequestConvertible, withJSONObject jsonObject: Any? = nil) throws -> URLRequest {
+        var urlRequest = try urlRequest.asURLRequest()
+
+        guard let jsonObject = jsonObject else { return urlRequest }
+
+        do {
+            let data = try JSONSerialization.data(withJSONObject: jsonObject, options: options)
+
+            if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil {
+                urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
+            }
+
+            urlRequest.httpBody = data
+        } catch {
+            throw AFError.parameterEncodingFailed(reason: .jsonEncodingFailed(error: error))
+        }
+
+        return urlRequest
+    }
 }
 
 // MARK: -

+ 32 - 2
Tests/ParameterEncodingTests.swift

@@ -646,8 +646,38 @@ class JSONParameterEncodingTestCase: ParameterEncodingTestCase {
                 } catch {
                     XCTFail("json should not be nil")
                 }
-            } else {
-                XCTFail("json should not be nil")
+            }
+        } catch {
+            XCTFail("Test encountered unexpected error: \(error)")
+        }
+    }
+
+    func testJSONParameterEncodeArray() {
+        do {
+            // Given
+            let array: [String] = ["foo", "bar", "baz"]
+
+            // When
+            let URLRequest = try encoding.encode(self.urlRequest, withJSONObject: array)
+
+            // Then
+            XCTAssertNil(URLRequest.url?.query)
+            XCTAssertNotNil(URLRequest.value(forHTTPHeaderField: "Content-Type"))
+            XCTAssertEqual(URLRequest.value(forHTTPHeaderField: "Content-Type"), "application/json")
+            XCTAssertNotNil(URLRequest.httpBody)
+
+            if let httpBody = URLRequest.httpBody {
+                do {
+                    let json = try JSONSerialization.jsonObject(with: httpBody, options: .allowFragments)
+
+                    if let json = json as? NSObject {
+                        XCTAssertEqual(json, array as NSObject)
+                    } else {
+                        XCTFail("json should be an NSObject")
+                    }
+                } catch {
+                    XCTFail("json should not be nil")
+                }
             }
         } catch {
             XCTFail("Test encountered unexpected error: \(error)")