Restofire is a protocol oriented networking client for Alamofire
Clone or download
Latest commit 64e68a7 Dec 11, 2018
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
.bundle release: 4.0.0 🎉 Feb 10, 2018
.github Update Template Feb 3, 2018
Assets Update Readme Feb 1, 2018
Carthage/Checkouts Update to Alamofire 5.0.0.beta.1 Dec 11, 2018
Example Update Example Dec 11, 2018
Restofire.playground Add watchOS Support Jan 31, 2018
Restofire.xcodeproj Use Restofire instead of AarKay as organisation Dec 11, 2018
Restofire.xcworkspace Update Alamofire Dec 11, 2018
Sources Refactor AOperation Dec 11, 2018
Tests Use Restofire instead of AarKay as organisation Dec 11, 2018
docs Update Docs Dec 11, 2018
scripts update travis yml Feb 3, 2018
.gitignore release: 4.0.0 🎉 Feb 10, 2018
.gitmodules Fix Quick And Nimble Submodules Feb 2, 2018
.jazzy.yml Update Travis yml Feb 3, 2018
.ruby-version release: 4.0.0 🎉 Feb 10, 2018
.swift-version Update Podspec May 14, 2018
.travis.yml Add Podrepo update Dec 12, 2018
CODE_OF_CONDUCT.md Create CODE_OF_CONDUCT.md Feb 1, 2018
CONTRIBUTING.md Update Template Feb 3, 2018
Cartfile Update to Alamofire 5.0.0.beta.1 Dec 11, 2018
Cartfile.private Remove Core Data Stack Dependency Jan 30, 2018
Cartfile.resolved Update to Alamofire 5.0.0.beta.1 Dec 11, 2018
Dangerfile Update Template Feb 3, 2018
Gemfile Update Template Feb 3, 2018
Gemfile.lock Updates Dec 11, 2018
LICENSE Update Readme Feb 1, 2018
Package.swift Update ReadMe Dec 11, 2018
Readme.md Update ReadMe Dec 11, 2018
Restofire.podspec Fix version podspec Dec 11, 2018

Readme.md

Restofire: A Protocol Oriented Networking Abstraction Layer in Swift

Platforms License

Swift Package Manager Carthage compatible CocoaPods compatible

Travis

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

Restofire is a protocol oriented networking client for Alamofire.

Features

  • Global Configuration for host / headers / parameters etc
  • Group Configurations
  • Per Request Configuration
  • Authentication
  • Response Validations
  • Custom Response Serializers like JSONDecodable
  • Isolate Network Requests from ViewControllers
  • Auto retry based on URLError codes
  • Request eventually when network is reachable
  • NSOperations
  • Complete Documentation

Requirements

  • iOS 10.0+ / Mac OS X 10.12+ / tvOS 10.0+ / watchOS 3.0+
  • Xcode 10

Installation

Dependency Managers

CocoaPods

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

$ gem install cocoapods

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

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

pod 'Restofire', '~> 5.0.0.alpha.1'

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 "Restofire/Restofire" ~> 5.0.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", .upToNextMajor(from: "5.0.0"))
    ]
)

Manually

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

Git Submodules

  • 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.

Embeded Binaries

  • Download the latest release from https://github.com/Restofire/Restofire/releases
  • 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.
  • Add the downloaded Restofire.framework & Alamofire.framework.
  • And that's it!

Configurations

Three levels of configuration

  • Global Configuration – The global configuration will be applied to all the requests. These include values like scheme, host, version, headers, sessionManager, callbackQueue, maxRetryCount, waitsForConnectivity etc.
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

    Restofire.Configuration.default.host = "httpbin.org"
    Restofire.Retry.default.retryErrorCodes = [.requestTimedOut,.networkConnectionLost]

    return true
}
  • Group Configuration – The group configuration inherits all the values from the global configuration. It can be used to group requests that have same behaviour but are different from the global configuration. For instance, If you have more than one host or if your global configuration has default url session and some requests require you to use ephemeral URL session.
import Restofire

protocol NYConfigurable: Configurable {}

extension NYConfigurable {

    public var configuration: Configuration {
        var configuration = Configuration.default
        configuration.scheme = "http://"
        configuration.host = "api.nytimes.com/svc/movies"
        configuration.version = "v2"
        return configuration
    }

}

protocol NYRequestable: Requestable, NYConfigurable {}
  • Per Request Configuration – The request configuration inherits all the values from the group configuration or directly from the global configuration.
import Restofire

struct MoviesReviewGETService: NYRequestable {

    typealias Response = [MovieReview]
    var path: String?
    var parameters: Any?

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

}

Usage

Making a Request

Requestable gives completion handler to enable making requests and receive response.

import Restofire

class ViewController: UITableViewController {

    var movieReviews: [MovieReview]!
    var requestOp: RequestOperation<MoviesReviewGETService>!

    func getReviews() {
        requestOp = MoviesReviewGETService(parameters: ["name": "Rahul Katariya"]).execute() {
            if let value = $0.result.value {
                self.movieReviews = value
            }
        }
    }

    deinit {
        requestOp.cancel()
    }

}

Isolating Network Requests from UIViewControllers

Requestable gives delegate methods to enable making requests from anywhere which you can use to store data in your cache.

import Restofire

struct MoviesReviewGETService: NYRequestable {

    ...

    static func loadMoviews() {
      MoviesReviewGETService(parameters: ["name": "Rahul Katariya"])
    }

    func request(_ request: RequestOperation<MoviesReviewGETService>, didCompleteWithValue value: [MovieReview]) {
      // Here you can store the results into your cache and then listen for changes inside your view controller.
    }

}

Custom Response Serializers

  • Decodable

By adding the following snippet in your project, All Requestable associatedType Response as Decodable will be decoded with JSONDecoder.

import Restofire

extension Restofire.ResponseSerializable where Response: Decodable {

    public var responseSerializer: AnyResponseSerializer<Result<Response>> {
        return AnyResponseSerializer<Result<Response>>
            .init(dataSerializer: { (request, response, data, error) -> Result<Response> in
                return Result { try DecodableResponseSerializer()
                    .serialize(request: request,
                               response: response,
                               data: data,
                               error: error)
                }
            })
    }

}
  • JSON

By adding the following snippet in your project, All Requestable associatedType Response as Any will be decoded with NSJSONSerialization.

import Restofire

extension Restofire.ResponseSerializable where Response == Any {

    public var responseSerializer: AnyResponseSerializer<Result<Response>> {
        return AnyResponseSerializer<Result<Response>>
            .init(dataSerializer: { (request, response, data, error) -> Result<Response> in
                return Result { try JSONResponseSerializer()
                    .serialize(request: request,
                               response: response,
                               data: data,
                               error: error)
                }
            })
    }

}

Wait for Internet Connectivity

Requestable gives you a property waitsForConnectivity which can be set to true. This will make the first request regardless of the internet connectivity. If the request fails due to .notConnectedToInternet, it will retry the request when internet connection is established.

struct PushTokenPutService: Requestable {

    typealias Response = Data
    ...
    var waitsForConnectivity: Bool = true

}

Contributing

Issues and pull requests are welcome!

Author

Rahul Katariya @rahulkatariya91

License

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