Latest 1.0.6
Homepage https://github.com/zsteed/NetworkRequest
License Apache License, Version 2.0 Licensed under the Apache License, Version 2.0 (the “License”);
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an “AS IS” BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

Platforms ios 9.0, requires ARC

Network Request

Network Request 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.
  • 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 NetworkRequest

// Parses result from API parsed into JSON
NetworkRequest(endpoint: "https://github.com").resultJSON { json in
    guard let json = json else { return }
    print(json)
}

// Parses result from API into a array of strings
NetworkRequest(endpoint: "https://github.com").resultCSV(qos: .userInteractive) { lines in
    guard let lines = lines else { return }
    print(lines)
}

// Returns raw data result from API, for you Codable Fans
NetworkRequest(endpoint: "https://github.com").resultData(qos: .userInitiated) { data in
    guard let data = data else { return }
    print(data)
}

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

// Returns cached file path
NetworkRequest(endpoint: "https://github.com").resultCachedFilePath(qos: .utility) { pathUrl in
    guard let pathUrl = pathUrl else { return }
    print(pathUrl)
}

// Returns codable type
NetworkRequest(endpoint: "www.google.com").resultModel(asType: [Foo].self, qos: .background) { foos in
    guard let foos = foos else { return }
    print(foos)
}

Private vs Global Queue

You can also set you own queue to be passed into the NetworkRequest Result
let bestQueue = OperationQueue.makePrivateQueue("bestYetQueue")

NetworkRequest(endpoint: "www.google.com").resultModel(asType: [Foo].self, qos: .background, queue: bestQueue) { foos in
    guard let foos = foos else { return }
    print(foos)
}

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

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 Request 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
///
NetworkRequest(
    endpoint: "UrlEndpoint",
    equivelanceId: "UniqueID",
    httpMethod: .GET,
    sessionType: .json,
    taskType: .dataTask,
    payload: Any,
    params: [:],
    headers: [:])

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 Request 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 NetworkRequest

class SimpleAuthNetworkRequest: NetworkRequest {

// Restore Session
override func restoreSession(completion: @escaping (_ success: Bool)->Void) {
    NetworkRequest(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
override func getAuthorizationToken() -> String {    
    return "AuthToken"
  }
}

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

If you need to work with multiple Authentication Tokens, just follow the same logic as listed above but add a enum to handle token state

import NetworkRequest

class ComplexAuthNetworkRequest: NetworkRequest {

  var tokenHandler: NewTokenHandler

  init(tokenHandler: NewTokenHandler,
    endpoint: String,
    equivelanceId: String = String(arc4random()),
    httpMethod: HTTPMethod = .GET,
    sessionType: SessionType = .json,
    taskType: TaskType = .dataTask,
    payload: Any? = nil,
    params: [String: String]? = nil,
    headers: [String:String]? = nil) {

    self.tokenHandler = tokenHandler

    super.init(endpoint: endpoint, equivelanceId: equivelanceId, httpMethod: httpMethod, sessionType: sessionType, taskType: taskType, payload: payload, params: params, headers: headers)
  }

  enum NewTokenHandler {
    case ninjaToken, happyToken
  }

  override func restoreSession(completion: @escaping (_ success: Bool)->Void) {
    switch tokenHandler {
    case .ninjaToken:
        NetworkRequest(endpoint: "https://www.RestoreNinjaSession.com").resultSuccess { error in
            if let error = error {
              print(error.localizedDescription)
              completion(false)
            } else {
              completion(true)
            }
         }      
    case .happyToken:
        NetworkRequest(endpoint: "https://www.RestoreNinjaSession.com").resultSuccess { error in
            if let error = error {
              print(error.localizedDescription)
              completion(false)
            } else {
              completion(true)
            }
        }
    }
}

  override func getAuthorizationToken() -> String {
    switch tokenHandler {
    case .ninjaToken:
      return "Basic"
    case .happyToken:
      return "ExpertMode"
    }
  }
}

Example Implementation:
ComplexAuthNetworkRequest(nth: .happyToken, endpoint: "www.google.com").resultJSON { json in
    guard let json = json else { return }
    print(json)
}

Installation

Cocoa Pods

In your PodFile add pod 'ZZNetworkRequest' example below.

use_frameworks!

target 'AppNameHere' do
  pod 'ZZNetworkRequest'
end

Latest podspec

{
    "name": "ZZNetworkRequest",
    "version": "1.0.6",
    "summary": "A wrapper on URLSession",
    "description": "A Wrapper on URLSession in combination with Operation Queue",
    "homepage": "https://github.com/zsteed/NetworkRequest",
    "license": {
        "type": "Apache License, Version 2.0",
        "text": "  Licensed under the Apache License, Version 2.0 (the "License");n  you may not use this file except in compliance with the License.n  You may obtain a copy of the License atnn  http://www.apache.org/licenses/LICENSE-2.0nn  Unless required by applicable law or agreed to in writing, softwaren  distributed under the License is distributed on an "AS IS" BASIS,n  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.n  See the License for the specific language governing permissions andn  limitations under the License.n"
    },
    "authors": "Zach Steed",
    "platforms": {
        "ios": "9.0"
    },
    "source": {
        "git": "https://github.com/zsteed/NetworkRequest.git",
        "tag": "1.0.6"
    },
    "source_files": "Sources/*.swift",
    "module_name": "NetworkRequest",
    "swift_version": "4.2",
    "requires_arc": true
}

Pin It on Pinterest

Share This