Last active
March 2, 2018 14:43
-
-
Save iAmrSalman/a63196e7498d2eb4ed4f4a5e1dda8877 to your computer and use it in GitHub Desktop.
[NetwokManager] #swift4 #Alamofire #ObjectMapper
This file contains hidden or 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
import UIKit | |
import Alamofire | |
import ObjectMapper | |
typealias NetworkSuccessClosure = (BaseModel?) -> Void | |
typealias NetworkFailureClosure = (Error?) -> Void | |
class NetworkManager: NSObject { | |
class func startRequest<T: BaseModel>(withRequestConfiguration request: RequestConfiguraton, andMappingObject objectClass: T?, successClouser success: NetworkSuccessClosure?, andFailure failure: NetworkFailureClosure?) { | |
if !serverReachable(forUrl: request.completeURL) { | |
failure?(KError.NetworkFaild(reason: .NoInternet(mandatory: request.connectionMandatory))) | |
request.failureClouser = failure | |
request.successClouser = success | |
if !LastRequest.request.lastRequests.contains(request){ | |
LastRequest.request.lastRequests.append(request) | |
} | |
#if DEBUG | |
print("☠️", "No internet") | |
#endif | |
return | |
} | |
#if DEBUG | |
print("🚀", request.requestMethod.rawValue, request.completeURL)) | |
#endif | |
Alamofire.request(request.completeURL, method: request.requestMethod, parameters: request.parameters, encoding: JSONEncoding.default, headers: request.headers).responseJSON { (response :DataResponse<Any>) in | |
switch response.result { | |
case .success(_): | |
if let data = response.result.value { | |
let model: BaseModel? | |
if let object = objectClass { | |
model = Mapper<T>().map(JSONObject: data, toObject: object) | |
} else { | |
model = Mapper<T>().map(JSONObject: data) | |
} | |
success?(model) | |
if LastRequest.request.lastRequests.count > 0 { | |
if let requestIndex = LastRequest.request.lastRequests.index(of: request) { | |
LastRequest.request.lastRequests.remove(at: requestIndex) | |
} | |
} | |
} | |
break | |
case .failure(_): | |
failure?(response.result.error) | |
break | |
} | |
} | |
} | |
class func restartRequest () { | |
for request in LastRequest.request.lastRequests { | |
#if DEBUG | |
print("♻️", request.requestMethod.rawValue, request.completeURL) | |
#endif | |
self.startRequest(withRequestConfiguration: request, andMappingObject: request.model, successClouser: request.successClouser, andFailure: request.failureClouser!) | |
} | |
} | |
class func serverReachable(forUrl url: String) -> Bool { | |
return NetworkReachabilityManager(host:url)!.isReachable | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment