Last active
December 19, 2017 16:44
-
-
Save luisburgos/70e8c105e3bdce1ab5b2536dc165bd56 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// RemoteDataSource.swift | |
// YellowPod | |
// | |
// Created by Luis Burgos on 11/24/17. | |
// Copyright © 2017 YellowPod. All rights reserved. | |
// | |
import Foundation | |
import Alamofire | |
import SwiftyJSON | |
protocol RemoteDataSource { | |
func serverRequest( | |
_ urlRequest: URLRequestConvertible, | |
_ parser: Parser?, | |
_ completion: @escaping (_ data: [APIModel]?, _ error : String?) -> Void | |
) | |
} | |
//MARK: - Generic Request | |
extension RemoteDataSource { | |
func serverRequest( | |
_ urlRequest: URLRequestConvertible, | |
_ parser: Parser? = nil, | |
_ completion: @escaping (_ data: [APIModel]?, _ error : String?) -> Void | |
) { | |
debugPrint("REQUEST") | |
Alamofire | |
.request(urlRequest) | |
.responseJSON { response in | |
debugPrint("RESPONSE") | |
//debugPrint(response) | |
switch response.result { | |
case .success: | |
if let value = response.result.value, (200..<300).contains(response.response!.statusCode) { | |
let json = JSON(value) | |
if let parser = parser { | |
do { | |
let data = try parser.parse(json) | |
completion(data, nil) | |
} catch let error as SerializationError { | |
debugPrint(error) | |
completion(nil, error.localizedDescription) | |
} catch { | |
completion(nil, "Error")//TODO: Extract | |
} | |
} else{ | |
completion(nil, nil) | |
} | |
} else { | |
//TODO: Handle error response | |
completion(nil, response.result.error?.localizedDescription) | |
} | |
case .failure(let error): | |
print(error) | |
completion(nil, error.localizedDescription) | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment