Latest 1.0
Homepage https://github.com/toohotz/HotzNetworkingManager
License MIT Please consider promoting this project if you find it useful.
The MIT License (MIT)
Copyright (c) 2016, Kemar White.
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Platforms ios 8.0, requires ARC
Dependencies Alamofire
Frameworks UIKit
Authors

CocoaPods
License


Personal Alamofire built upon wrapper for web server API endpoint requests with Result closure callback for more succinct error handling. Utilizing the Facade pattern ensures only one networking manager instance exists per app life cycle. This framework wrapper was created wtih the intention of making web server endpoint requests faster to setup and easily customizable.

Dependencies

  • Alamofire – HTTP networking library written in Swift.

Requirements

  • iOS 8.0+ / Mac OS X 10.9+ / tvOS 9.0+ / watchOS 2.0+
  • Xcode 7.2+

Installation


CocoaPods

source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '8.0'
use_frameworks!
pod 'Alamofire'
pod 'HTZNetworkingManager'

Afterwards run a pod install.

$ pod install

Manually

If project integration is your style (which I have personally done in a current project due to Xcode 7+ and Cocoapod issue with physical device testing).

Embedded Framework

  • Initialize a git repo in the root of your project directory if you have not done so already.
  • Add HTZNetworkingManager
    $ git submodule add https://github.com/toohotz/HotzNetworkingManager.git

    Open HTZNetworkingManager folder and drag the project file named HTZNetworkingManager.xcodeproj into your application’s Xcode project.

Img1

Usage

After importing the module, making requests are similar to how requests are made using Alamofire.
Since we are expecting to be dealing with endpoint requests, we instantiate a baseURL that will be used as endpoints are appended to form the URL for a given request. Note: Requests will fail to execute if the baseURL has not been set prior to making an API call.

Once set, instantiate an instance of HTZNetworkingFacade.sharedInstance and assign a baseURL.

From here, making requests works in a similar fashion to Alamofire requests like so:

let networkingFacade = HTZNetworkingFacade.sharedInstance
networkingFacade.networkingManager.getDataFromEndPoint(“/someEndpoint”) { (responseData) -> () in
}

If you have not dabbed with Alamofire since 3.0 with its new type Result , utilizing functional programming we can now work with expected results rather than an optional which is for the better for two main reasons.

  • We can expect our result to exist if our closure returns a success for the Result value
  • In the event of an error, we are forced due to the Result type to handle our errors in code as it is tied to the closure Result type that we are expecting

Since error checking is compile time enforced, error handling for your specific API calls should also handle most (ideally all) of the possible errors that can occur relating to your network request being made.

Response data handling

Since code speaks better, handling a typical response would look like so:

switch responseData {
case .Success(let validResponse):
// Do something with the response received
case .Failure(let NetworkingError.ResponseError(errorDescription)):
// Handle the error accordingly
}

And that’s it.

Using the framework to handle responses is great but becomes better when subclassed to better handle the expected responses.

Example

A class that will be used to retrieve the Users for our application.

class UserbaseFacade: HTZNetworkingFacade

Override the initializer to set the baseURL.

self.networkingManager.baseURL = UserBaseFacadeEndpoint.baseURL.rawValue

Here you’ll notice that an enum is being used here, within the subclasses it is handy to use enum with raw values of strings as opposed to multiple string constants to easily keep track of specific endpoints like so


enum UserBaseFacadeEndpoint: String {
    case baseURL = "someBaseURL"
    case retrieveAllUsers = "/getAllUsers"
    case getUser = "/getUser/"
}

Then we can wrap our subclass APIs around the underlying frameworks’s API calls like so

Making the API

func retrieveAllUsers(userData: Result<[Users], UserNetworkError> -> () )
{

}

Here our expected response will be either a list of users or a custom error object that should handle all of our possible errors with a last case to handle an unexpected error (such as from the network itself). An example of that would look like this:

enum UserNetworkError: ErrorType {
    case NoUsersFound
    // Our unexpected error handling case here
    case SearchRequestFailed(String)
}

The body of our API would then look like so:

// Make the call to the underlying networking API
self.networkingManager.getDataFromEndPoint(UserbaseFacadeEndpoint.retrieveAllUsers.rawValue) { (responseData) -> () in 
    switch responseData {
    case .Success(let rawUserData):
    // Parse the data *NOTE for example sake we are just casting our response to the desired callback type*
    let parsedUsers = rawUserData as! [Users]
    // Here we check if no users were returned we callback with our custom .NoUsersFound error
    if parsedUsers?.isEmpty == true {
                    userData(.Failure(UserNetworkError.NoUsersFound))
    }
    userData(.Success(parsedUsers))

    // Our default error handling case

    case .Failure(let NetworkingError.ResponseError(responseError)):
    // Passing along the error description that we received
    userData(.Failure(UserNetworkError.SearchRequestFailed(responseError))
    }
}

Handling the response

From a View Controller that is looking for a list of users to update its tableview with, our API call to retrieve those users would look like this:

let userFacade = UserBaseFacade()

userFacade.retrieveAllUsers{ (userResponse) -> () in 
    switch userResponse {
    case .Success(let users):
    // Do something with the list of users
    case .Failure(let UserNetworkError.NoUsersFound):
    print("No users were found.")
    case .Failure(let UserNetworkError.SearchRequestFailed(responseString)):
    print(responseString)
    }
}

Todo

  • Integrate JSON response handling

Credits

Much goes out to the Alaofire Software Foundation for being the bedrock of how this framework wrapper functions.

Latest podspec

{
    "name": "HTZNetworkingManager",
    "version": "1.0",
    "summary": "Personal Alamofire built upon wrapper for faster CRUD API endpoint requests with *Result* closure callback for more succinct error handling.",
    "license": {
        "type": "MIT",
        "text": "    Please consider promoting this project if you find it useful.n    The MIT License (MIT)n    Copyright (c) 2016, Kemar White.n    Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:n    The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.n    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.n"
    },
    "authors": {
        "Kemar White": "[email protected]"
    },
    "platforms": {
        "ios": "8.0"
    },
    "source": {
        "git": "https://github.com/toohotz/HotzNetworkingManager.git",
        "tag": "1.0"
    },
    "homepage": "https://github.com/toohotz/HotzNetworkingManager",
    "source_files": "HTZNetworkingManager/**/*.{swift}",
    "frameworks": "UIKit",
    "requires_arc": true,
    "dependencies": {
        "Alamofire": []
    }
}

Pin It on Pinterest

Share This