Monday, 15 May 2017

Better Network Request

For the result we can better create an enum to decide the case enum Result<T> {
case success(T)
case error
}

Now let’s create another enum to handle our JSON response which can be an array of objects or a simple one. We are going to use a type alias JsonObject, so don’t forget to declare typealias JsonObject = [String: Any]

enum Json {
case object(_: JsonObject)
case array(_: [JsonObject])
init?(json: Any) {
if let object = json as? JsonObject {
self = .object(object)
return
}
if let array = json as? [JsonObject] {
self = .array(array)
return
}
return nil
}
}
If you take a better look you will see that our completion returns a Result<T> which T is a Json . What this exactly mean? If our request reaches the server our result will be a success and it will return a Jsonassociated. Remember that our Json can contain an object or array.
Now we create our RealNetworkRequest that will implement our NetworkRequest protocol. This is the wrapper that we are going to build around Alamofire.
class RealNetworkRequest: NetworkRequest {
func request(_ url: URL, method: HTTPMethod, parameters: [String : Any]?, headers: [String : String]?, completion: @escaping (Result<Json>) -> Void) {
Alamofire.request(url,
method: method,
parameters: parameters,
encoding: URLEncoding.default,
headers: headers).responseJSON(completionHandler: { (response) in
if let value = response.result.value, let result = Json(json: value) {
completion(.success(result))
} else {
completion(.error)
}
})
}
}