Skip to content

Networking

Ayush Awasthi edited this page Dec 28, 2018 · 4 revisions

As developers we all know that working with hardcoded strings is unreliable as one simple spelling mistake can cause big problems, Networking module is made with the approach that each network call response must be bind in a model of itself. This reduces use of strings and which in turn reduces chances of unexpected behaviours of app.

NetworkManager class is written on top of Alamofire library, but can be updated easily to use any other networking library or even just use URLSession. This make the code easy to update, whenever there is new version available, only one class needs to be updated and all the code in app works as it is.

Networking module is made up of following components:

URLRequestConvertible

URLRequestConvertible is a protocol with just one method inside:

protocol URLRequestConvertible {  
   func asURLRequest() -> URLRequest?  
}  

APIConfigurable

APIConfigurable is protocol that extends URLRequestConvertible and adds more methods on top of it. This protocol also has default definition for asURLRequest().

protocol APIConfigurable: URLRequestConvertible {
    var type: RequestType
    var path: String
    var parameters: [String: Any]
    var headers: [String: String]?
}

The intended use for this protocol is as follows:

enum OnboardingEndPoint: APIConfigurable {
    case login(email: String, password: String)
    case signup(name: String?, email: String, password: String)

    var headers: [String: String]? {
        return ["Authorization": "<token>"]
    }
    var type: RequestType {
        return .POST
    }
    var parameters: [String: Any] {
        switch self {
           case .login(let email, let password):
                return ["Email": email, "Password": password]
           case .signup(let name, let email, let password):
                return ["Name": name ?? "", "Email": email, "Password": password]
        }
    }
    var path: String {
        switch self {
           case .login:
                return "https://www.myserver.com/login"
           case .signup:
                return "https://www.myserver.com/signup"
        }      
    }
}

Now the above enum can be easily used with NetworkManager or with any networking library that accepts URLRequest to make URLRequest as follows

let request = OnboardingEndPoint.login(email: "ayush", password: "123456").asURLRequest()

Clone this wiki locally