Latest 0.0.4
Homepage https://github.com/zsteed/NetOperations
License MIT
Platforms ios 9.0

Network Operations made easy

Network Operation is a networking library written on top of URL Session.

  • Gives Control over URL Session, Requests can be very simple or complex.
  • Built on top of operation queue.
  • Gives ability to control Quality of Service .
  • Gives option handle duplicate requests sent.
  • Gives power to handle operation dependencies

  • Handles parsing for you, depending on type specified.
  • CSV, JSON, RAW DATA, CODABLE, CACHEPATH, SUCCESS

  • Handles attempt count, will try endpoint 3 times for you if 200…299 is not acheived.

  • Easy Subclass capability to handle restoring expired auth token / session.
  • If the API returns a 401 , this will be handled by the class, once restored, it will reset attempt count and retry request

Example Code Basic:

// import NetOperations

// Parses result from API parsed into JSON
NetworkOperation(endpoint: "https://github.com").resultJSON { json in
    print(json!)
}

// Parses result from API into a array of strings
NetworkOperation(endpoint: "https://github.com").resultCSV(qos: .userInteractive) { lines in
    print(lines!)
}

// Returns raw data result from API, for you Codable Fans
NetworkOperation(endpoint: "https://github.com").resultData(qos: .userInitiated) { data in
    print(data!)
}

// Returns error == nil if HTTP Status code is in range 200...299
NetworkOperation(endpoint: "https://github.com").resultSuccess(qos: .background) { error in
    guard error == nil else { return }
    print("Success")
}

// Returns cached file path
NetworkOperation(endpoint: "https://github.com").resultCachedFilePath(qos: .utility) { pathUrl in
    print(pathUrl!)
}

// Returns codable type
NetworkOperation(endpoint: "www.google.com").resultModel(asType: [Foo].self, qos: .background) { foos in
    print(foos!)
}

Private vs Global Queue

// You can also set you own queue to be passed into the NetworkOperation Result

let bestQueue = NetworkQueue(queueName: "bestYetQueue")

NetworkOperation(endpoint: "www.google.com").resultModel(asType: [Foo].self, 
                                                         qos: .background,
                                                         queue: bestQueue) { foos in    
    print(foos!)
}

If you don't pass in your own queue it will default to a single "globalQueue"

Available Parameters

Those examplse are very basic, if you want more control you are given the option to customize URL Session as you wish
Here are the Network Operation Init Parameters

///
/// - parameter endpoint: The url endpoint
/// - parameter equivelanceId: The ID used to check for duplicate operation entries
/// - parameter httpMethod: GET,POST,PUT,DELETE
/// - parameter sessionType: URL Session type:  Ephemeral, Binary, JSON
/// - parameter taskType: URL Session Task Type: DataTask, UploadTask, DownloadTask
/// - parameter payload: Add to POST HTTP methods
/// - parameter params: Parameters to add to the URL endpoint
/// - parameter headers: Additional headers that can be added to a url session
///
NetworkOperation(
    endpoint: "UrlEndpoint",
    equivelanceId: "UniqueID",
    httpMethod: .GET,
    sessionType: .json,
    taskType: .dataTask,
    payload: Any,
    params: [:],
    headers: [:]
)

Handling dependencies

let firstOp = NetworkOperation(endpoint: "http://github.com").resultJSON { json in
    print("First operation executed")
}

let secondOp = NetworkOperation(endpoint: "www.test.com")
secondOp.resultSuccess(dependentOnOperations: [firstOperation]) { errorString in
    print("Second to be executed")
}

let doneBlock = BlockOperation {
    print("Executed when both operations are finished")
}

doneBlock.addDependency(secReq)
NetworkQueue.globalQueue.addOperation(doneBlock)

Handle Caching images in folder

This code handles fetching images from the endpoint provided. This method will cache the images in the FileManager

NetworkOperation(endpoint: "www.google.com").resultImage(docCacheType: .cache) { imageData in
    print(imageData!)
}

// You can clear cache or document images
NetworkOperation.clearCacheImages()
NetworkOperation.clearDocumentImages()

Adding in Authentication

  • Note: You of course can add the Authentication header in the headers paramter but who likes re-writing code over and over?

Say you want to add an authorization header to every API call, just SubClass Network Operation and override these 2 methods.

  • Then authentiaction header will be added for you and re-authenticating will be handled for you if a 401 is received
import 

class AuthNetworkOperation: NetworkOperation {

    // Restore Session logic
    override func restoreSession(completion: @escaping (_ success: Bool)->Void) {
        NetworkOperation(endpoint: "https://www.Restoresession.com").resultSuccess { error in
            if let error = error {
                print(error.localizedDescription)
                completion(false)
            } else {
                completion(true)
            }
        }
    }

    // Get your local saved auth token to pass into headers of all `AuthNetworkOperation` objects
    override func getAuthorizationToken() -> String {    
        return "AuthToken"
    }
}

// Then use this class just like you would the `NetworkOperation` class
AuthNetworkOperation(endpoint: "www.google.com").resultSuccess { error in
    guard error == nil else { return }
    print("success")
}

Installation

Cocoa Pods

In your PodFile add pod 'NetOperations' example below.

use_frameworks!

target 'InsertAppNameHere' do
pod 'NetOperations'
end

Carthage

In your Cartfile specify

github "zsteed/NetOperations" ~> 0.0.4

Visit https://github.com/Carthage/Carthage for more information on how to set up Carthage.

Latest podspec

{
    "name": "NetOperations",
    "version": "0.0.4",
    "summary": "Light weight networking.",
    "homepage": "https://github.com/zsteed/NetOperations",
    "authors": "Zach Steed",
    "platforms": {
        "ios": "9.0"
    },
    "swift_version": "4.2",
    "source": {
        "git": "https://github.com/zsteed/NetOperations.git",
        "tag": "0.0.4"
    },
    "source_files": "Sources/*.swift",
    "license": {
        "type": "MIT",
        "file": "LICENSE"
    },
    "description": "A light weight wrapper on URL Session and Operations."
}

Pin It on Pinterest

Share This