Skip to content

Commit 6636f57

Browse files
author
burak.uzunboy
committed
Now ResponseBodyParsable conforms Codable
1 parent a51ac25 commit 6636f57

4 files changed

Lines changed: 35 additions & 54 deletions

File tree

Package.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,6 @@ let package = Package(
2424
dependencies: ["CoreUsefulSDK"]),
2525
// .testTarget(
2626
// name: "iOSUsefulNetworkLayerTests",
27-
// dependencies: ["iOSUsefulNetworkLayer", "iOSCoreUsefulSDK"]),
27+
// dependencies: ["UsefulNetworkLayer", "CoreUsefulSDK"]),
2828
]
2929
)

Sources/UsefulNetworkLayer/NetworkLayer/APIConfiguration.swift

Lines changed: 14 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -182,52 +182,22 @@ public struct APIConfiguration<T> where T: ResponseBodyParsable {
182182
}
183183

184184
/**
185-
The response objects should be inherited from the `ResponseBodyParsable` to operate by the `NetworkLayer`.
186-
*/
187-
open class ResponseBodyParsable: NSObject, NSDiscardableContent {
188-
189-
/// Returns creation date of the response by the `NetworkLayer`.
190-
public private(set) var creationDate: Date
191-
192-
/// Override this initializer to create responses from the `Data`.
193-
/// - parameter data: The response represented as `Data`
194-
required public init?(_ data: Data) {
195-
self.creationDate = Date()
196-
}
197-
198-
/// Override this initializer to create responses from the `JSON` object.
199-
/// - parameter response: The `JSON` object as `Any` type which could be casted to `Dictionary` or `Array`
200-
required public init?(_ response: Any?) {
201-
self.creationDate = Date()
202-
}
203-
204-
/// Returns `true` in default.
205-
public func beginContentAccess() -> Bool {
206-
print("\(self.typeName): Content access successful")
207-
return true
208-
}
209-
210-
/// Doesn't do anything in default.
211-
public func endContentAccess() {
212-
print("\(self.typeName): Content cannot be accessed anymore")
213-
}
214-
215-
/// Doesn't do anything in default.
216-
public func discardContentIfPossible() {
217-
print("\(self.typeName): Discard content called")
218-
}
219-
220-
/// Returns `false` in default.
221-
public func isContentDiscarded() -> Bool {
222-
return false
223-
}
224-
225-
/// Return specified parameter to work with `autoCache` API requests.
226-
public func cachingEndsAt() -> Date? {
227-
return nil
228-
}
185+
The response objects should be inherited from the `ResponseBodyParsable` to operate by the `NetworkLayer`.
186+
*/
187+
public protocol ResponseBodyParsable: Codable, NameDescribeable {
188+
/// To allow `NetworkLayer` to use defined initializer, set `true`, otherwise `Codable` protocol will be used.
189+
static var shouldUseCustomInitializer: Bool { get }
190+
/// Use this initializer to allow custom parsing from JSON object.
191+
init?(response: Any?)
192+
/// Use this initializer to allow custom parsing from Data directly.
193+
init?(data: Data)
194+
/// If custom value is defined, Caching will use this method to detect expiry.
195+
func cachingEndsAt() -> Date?
229196
}
230197

198+
public extension ResponseBodyParsable {
199+
func cachingEndsAt() -> Date? { return nil }
200+
}
231201

232202
/// Response of the API if request is completed successfully.
233203
public struct APIResponse<T> where T: ResponseBodyParsable {

Sources/UsefulNetworkLayer/NetworkLayer/NetworkLayer.swift

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -198,7 +198,18 @@ public class NetworkLayer: NSObject, URLSessionDataDelegate {
198198
request: APIConfiguration<T>,
199199
completion: @escaping (Result<T>)->()) where T: ResponseBodyParsable {
200200

201-
if let dataObject = request.responseBodyObject.init(data) {
201+
if !request.responseBodyObject.shouldUseCustomInitializer {
202+
do {
203+
let jsonObject = try JSONDecoder().decode(request.responseBodyObject, from: data)
204+
completion(.success(.init(response: response, responseBody: jsonObject)))
205+
} catch {
206+
completion(.error(.init(request: request, error: error as NSError)))
207+
}
208+
209+
return
210+
}
211+
212+
if let dataObject = request.responseBodyObject.init(data: data) {
202213
self.sendLog(message: "Data Object created from Operation: \(operationId) - Object: \(dataObject.typeName)")
203214
if request.autoCache, let cacheTiming = dataObject.cachingEndsAt() {
204215
self._cache?.changeCacheExpiry(for: request.request!, to: cacheTiming)
@@ -211,7 +222,7 @@ public class NetworkLayer: NSObject, URLSessionDataDelegate {
211222

212223
do {
213224
let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments)
214-
if let responseObject = request.responseBodyObject.init(json) {
225+
if let responseObject = request.responseBodyObject.init(response: json) {
215226
self.sendLog(message: "Response Object Created from JSON Data with Operation: \(operationId) - Object: \(responseObject.typeName)")
216227
if request.autoCache, let cacheTiming = responseObject.cachingEndsAt() {
217228
self._cache?.changeCacheExpiry(for: request.request!, to: cacheTiming)

Tests/iOSUsefulNetworkLayerTests/iOSUsefulNetworkLayerTests.swift

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import XCTest
2-
@testable import iOSUsefulNetworkLayer
2+
@testable import UsefulNetworkLayer
33

44
final class iOSUsefulNetworkLayerTests: XCTestCase {
55
func testExample() {
@@ -31,7 +31,7 @@ final class iOSUsefulNetworkLayerTests: XCTestCase {
3131
case .error(let err):
3232
XCTFail("Error: \(err.error.localizedDescription)")
3333
break
34-
case .success(_):
34+
case .success(let obj):
3535
exp.fulfill()
3636
}
3737
}
@@ -47,26 +47,26 @@ final class iOSUsefulNetworkLayerTests: XCTestCase {
4747

4848
class ExampleResponseObject: ResponseBodyParsable {
4949

50+
static var shouldUseCustomInitializer: Bool { return false }
5051
var userId: Int
5152
var id: Int
5253
var title: String
5354
var completed: Bool
5455

55-
required init?(_ data: Data) {
56+
required init?(data: Data) {
5657
return nil
5758
}
58-
59-
required init?(_ response: Any?) {
59+
60+
required init?(response: Any?) {
6061
guard let dict = response as? [String:Any] else { return nil }
6162
guard let userId = dict["userId"] as? Int,
6263
let id = dict["id"] as? Int,
6364
let title = dict["title"] as? String,
6465
let completed = dict["completed"] as? Bool else { return nil }
65-
66+
6667
self.userId = userId
6768
self.id = id
6869
self.title = title
6970
self.completed = completed
70-
super.init(response)
7171
}
7272
}

0 commit comments

Comments
 (0)