Restofire: A Protocol Oriented Networking Abstraction Layer in Swift

Restofire

Platforms License

Swift Package Manager Carthage compatible CocoaPods compatible

Travis

Join the chat at https://gitter.im/Restofire/Restofire

Restofire is a protocol oriented network abstraction layer in swift that is built on top of Alamofire to use services in a declartive way.

Features

  • [x] No Learning Curve
  • [x] Default Configuration for Base URL / headers / parameters etc
  • [x] Multiple Configurations
  • [x] Single Request Configuration
  • [x] Custom Response Serializer
  • [x] Authentication
  • [x] Response Validations
  • [x] Request NSOperation
  • [x] RequestEventuallyOperation with Auto Retry
  • [x] Complete Documentation
  • [x] Tutorial

Requirements

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

Installation

CocoaPods

CocoaPods is a dependency manager for Cocoa projects. You can install it with the following command:

$ gem install cocoapods

CocoaPods 1.1.0+ is required to build Restofire 2.0.0+.

To integrate Restofire into your Xcode project using CocoaPods, specify it in your Podfile:

source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '9.0'
use_frameworks!

pod 'Restofire', '~> 2.0'

Then, run the following command:

$ pod install

Carthage

Carthage is a decentralized dependency manager that automates the process of adding frameworks to your Cocoa application.

You can install Carthage with Homebrew using the following command:

$ brew update
$ brew install carthage

To integrate Restofire into your Xcode project using Carthage, specify it in your Cartfile:

github "RahulKatariya/Restofire" ~> 2.0

Swift Package Manager

To use Restofire as a Swift Package Manager package just add the following in your Package.swift file.

import PackageDescription

let package = Package(
    name: "HelloRestofire",
    dependencies: [
        .Package(url: "https://github.com/Restofire/Restofire.git", versions: Version(2, 0, 0)..<Version(3, 0, 0))
    ]
)

Manually

If you prefer not to use either of the aforementioned dependency managers, you can integrate Restofire into your project manually.

Embedded Framework

  • Open up Terminal, cd into your top-level project directory, and run the following command if your project is not initialized as a git repository:
$ git init
  • Add Restofire as a git submodule by running the following command:
$ git submodule add https://github.com/Restofire/Restofire.git
$ git submodule update --init --recursive
  • Open the new Restofire folder, and drag the Restofire.xcodeproj into the Project Navigator of your application’s Xcode project.

    It should appear nested underneath your application’s blue project icon. Whether it is above or below all the other Xcode groups does not matter.

  • Select the Restofire.xcodeproj in the Project Navigator and verify the deployment target matches that of your application target.

  • Next, select your application project in the Project Navigator (blue project icon) to navigate to the target configuration window and select the application target under the Targets heading in the sidebar.

  • In the tab bar at the top of that window, open the General panel.

  • Click on the + button under the Embedded Binaries section.

  • You will see two different Restofire.xcodeproj folders each with two different versions of the Restofire.framework nested inside a Products folder.

    It does not matter which Products folder you choose from.

  • Select the Restofire.framework & Alamofire.framework.

  • And that’s it!

The Restofire.framework is automagically added as a target dependency, linked framework and embedded framework in a copy files build phase which is all you need to build on the simulator and a device.


Usage

Global Configuration

import Restofire

class AppDelegate: UIResponder, UIApplicationDelegate {

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        // Override point for customization after application launch.

        Restofire.defaultConfiguration.baseURL = "http://www.mocky.io/v2/"
        Restofire.defaultConfiguration.headers = ["Content-Type": "application/json"]
        Restofire.defaultConfiguration.logging = true
        Restofire.defaultConfiguration.authentication.credential = URLCredential(user: "user", password: "password", persistence: .forSession)
        Restofire.defaultConfiguration.validation.acceptableStatusCodes = Array(200..<300)
        Restofire.defaultConfiguration.validation.acceptableContentTypes = ["application/json"]
        Restofire.defaultConfiguration.retry.retryErrorCodes = [.timedOut,.networkConnectionLost]
        Restofire.defaultConfiguration.retry.retryInterval = 20
        Restofire.defaultConfiguration.retry.maxRetryAttempts = 10
        let sessionConfiguration = URLSessionConfiguration.default
        sessionConfiguration.timeoutIntervalForRequest = 7
        sessionConfiguration.timeoutIntervalForResource = 7
        sessionConfiguration.httpAdditionalHeaders = Alamofire.SessionManager.defaultHTTPHeaders
        Restofire.defaultConfiguration.sessionManager = Alamofire.SessionManager(configuration: sessionConfiguration)

        return true
  }

}

Creating a Service


import Restofire

struct PersonGETService: Requestable {

    typealias Model = [String: Any]
    var path: String = "56c2cc70120000c12673f1b5"

}

Consuming the Service

import Restofire

class ViewController: UIViewController {

    var person: [String: Any]!
    var requestOp: DataRequestOperation<PersonGETService>!

    func getPerson() {
        requestOp = PersonGETService().executeTask() {
            if let value = $0.result.value {
                self.person = value
            }
        }
    }

    deinit {
        requestOp.cancel()
    }

}

URL Level Configuration


protocol HTTPBinConfigurable: Configurable { }

extension HTTPBinConfigurable {

    var configuration: Configuration {
        var config = Configuration()
        config.baseURL = "https://httpbin.org/"
        config.logging = Restofire.defaultConfiguration.logging
        return config
    }

}

protocol HTTPBinValidatable: Validatable { }

extension HTTPBinValidatable {

  var validation: Validation {
    var validation = Validation()
    validation.acceptableStatusCodes = Array(200..<300)
    validation.acceptableContentTypes = ["application/json"]
    return validation
  }

}


protocol HTTPBinRetryable: Retryable { }

extension HTTPBinRetryable {

  var retry: Retry {
    var retry = Retry()
    retry.retryErrorCodes = [.timedOut,.networkConnectionLost]
    retry.retryInterval = 20
    retry.maxRetryAttempts = 10
    return retry
  }

}

Creating the Service


import Restofire
import Alamofire

struct HTTPBinPersonGETService: Requestable, HTTPBinConfigurable, HTTPBinValidatable, HTTPBinRetryable {

    typealias Model = [String: Any]
    let path: String = "get"
    let encoding: ParameterEncoding = URLEncoding.default
    var parameters: Any?

    init(parameters: Any?) {
        self.parameters = parameters
    }

}


Consuming the Service

import Restofire

class ViewController: UIViewController {

    var person: [String: Any]!
    var requestOp: DataRequestOperation<HTTPBinPersonGETService>!

    func getPerson() {
        requestOp = HTTPBinPersonGETService(parameters: ["name": "Rahul Katariya"]).executeTask() {
            if let value = $0.result.value {
                self.person = value
            }
        }
    }

    deinit {
        requestOp.cancel()
    }

}

Request Level Configuration


import Restofire
import Alamofire

struct MoviesReviewGETService: Requestable {

    typealias Model = Any
    var host: String = "http://api.nytimes.com/svc/movies/v2/"
    var path: String = "reviews/"
    var parameters: Any?
    var encoding: ParameterEncoding = URLEncoding.default
    var method: Alamofire.HTTPMethod = .get
    var headers: [String: String]? = ["Content-Type": "application/json"]
    var manager: Alamofire.SessionManager = {
        let sessionConfiguration = URLSessionConfiguration.default
        sessionConfiguration.timeoutIntervalForRequest = 7
        sessionConfiguration.timeoutIntervalForResource = 7
        sessionConfiguration.httpAdditionalHeaders = SessionManager.defaultHTTPHeaders
        return Alamofire.SessionManager(configuration: sessionConfiguration)
    }()
    var queue: DispatchQueue? = DispatchQueue.main
    var logging: Bool = Restofire.defaultConfiguration.logging
    var credential: URLCredential? = URLCredential(user: "user", password: "password", persistence: .forSession)
    var acceptableStatusCodes: [Int]? = Array(200..<300)
    var acceptableContentTypes: [String]? = ["application/json"]
    var retryErrorCodes: Set<URLError.Code> = [.timedOut,.networkConnectionLost]
    var retryInterval: TimeInterval = 20
    var maxRetryAttempts: Int = 10

    init(path: String, parameters: Any) {
        self.path += path
        self.parameters = parameters
    }

}

// MARK: - Caching
import RealmSwift
import SwiftyJSON

extension MoviesReviewGETService {

    func didCompleteRequestWithDataResponse(dataResponse: DataResponse<Model>) {
        guard let model = response.result.value else { return }
        let realm = try! Realm()
        let jsonMovieReview = JSON(model)
        if let results = jsonMovieReview["results"].array {
            for result in results {
                let movieReview = MovieReview()
                movieReview.displayTitle = result["display_title"].stringValue
                movieReview.summary = result["summary_short"].stringValue
                try! realm.write {
                    realm.add(movieReview, update: true)
                }
            }
        }
    }

}

RequestEventually Service


import Restofire

class MoviesReviewTableViewController: UITableViewController {

  let realm = try! Realm()
  var results: Results<MovieReview>!
  var notificationToken: NotificationToken? = nil

  override func viewDidLoad() {
      super.viewDidLoad()

      MoviesReviewGETService(path: "all.json", parameters: ["api-key":"sample-key"])
          .executeTaskEventually()

      results = realm.objects(MovieReview)

      notificationToken = results.addNotificationBlock { [weak self] (changes: RealmCollectionChange) in
          guard let _self = self else { return }
          switch changes {
          case .Initial, .Update(_, deletions: _, insertions: _, modifications: _):
              _self.results = _self.realm.objects(MovieReview)
              _self.tableView.reloadData()
          default:
              break
          }
      }

  }

  deinit {
      notificationToken = nil
  }

}

Examples

License

Restofire is released under the MIT license. See LICENSE for details.