I want to create my own network manager class so that I could handle the errors globally like there is no internet then I can show pop-ups from that class only. I am using Alamofire for this and also want to parse the data in JSON with the help of swiftjson library. I have tried with my code but not able to pass the data from my network class to where the function is being called.
import UIKit
import Alamofire
import SwiftyJSON
import SystemConfiguration
class WebServiceHelper: NSObject {
typealias SuccessHandler = (JSON) -> Void
typealias FailureHandler = (Error) -> Void
// MARK: - Internet Connectivity
class func isConnectedToNetwork() -> Bool {
var zeroAddress = sockaddr_in()
zeroAddress.sin_len = UInt8(MemoryLayout<sockaddr_in>.size)
zeroAddress.sin_family = sa_family_t(AF_INET)
guard let defaultRouteReachability = withUnsafePointer(to: &zeroAddress, {
$0.withMemoryRebound(to: sockaddr.self, capacity: 1) {
SCNetworkReachabilityCreateWithAddress(nil, $0)
}
}) else {
return false
}
var flags: SCNetworkReachabilityFlags = []
if !SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) {
return false
}
let isReachable = flags.contains(.reachable)
let needsConnection = flags.contains(.connectionRequired)
return (isReachable && !needsConnection)
}
// MARK: - Helper Methods
class func getWebServiceCall(_ strURL : String, isShowLoader : Bool, success : @escaping SuccessHandler, failure : @escaping FailureHandler) {
if isConnectedToNetwork() {
print(strURL)
if isShowLoader == true {
//AppDelegate.getDelegate().showLoader()
}
AF.request(strURL).responseJSON { (resObj) -> Void in
print(resObj.result)
}
}else {
//CommonMethods.showAlertWithError("", strMessage: Messages.NO_NETWORK, withTarget: (AppDelegate.getDelegate().window!.rootViewController)!)
}
}
}
// calling from the controller
func getData() {
WebServiceHelper.getWebServiceCall("http://3.16.229.165/webservice/getFollowingList", isShowLoader: false, success: { (responceObj) in
print("success => \(responceObj)")
}
, failure: { (failureObj) in
print("failureObj = \(failureObj)")
})
}
// API response data
{
"status": false,
"followers": false,
"message": "You are not yet following anyone"
}
You miss success(value)
AF.request(strURL).responseJSON { (resObj) -> Void in
switch resObj.result {
case .success(let value):
let res = JSON(value)
success(res)
case .failure(let error):
failure(error)
}
}