Giter Club home page Giter Club logo

restofire's Introduction

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 Twitter

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

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

Requirements

  • iOS 8.0+ / Mac OS X 10.10+ / tvOS 9.0+ / watchOS 2.0+
  • Xcode 8+
  • Swift 3.1+

Installation

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, '8.0'
use_frameworks!

pod 'Restofire', '~> 2.3.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.3.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", majorVersion: 2, minorVersion: 3)
    ]
)

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!

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.logging = true

        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.

restofire's People

Contributors

rahul0x24 avatar gitter-badger avatar

Watchers

Silvia Man avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.