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 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', '~> 3.0.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 "Restofire/Restofire" ~> 3.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", 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 commandif
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 theRestofire.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 theEmbedded Binaries
section.You will see two different
Restofire.xcodeproj
folders each with two different versions of theRestofire.framework
nested inside aProducts
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 theEmbedded 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.Configuration.default.scheme = "http://"
Restofire.Configuration.default.baseURL = "www.mocky.io"
Restofire.Configuration.default.version = "v2"
return true
}
}
Creating a Service
import Restofire
struct PersonGETService: Requestable {
typealias Response = [String: Any]
var path: String? = "56c2cc70120000c12673f1b5"
}
Consuming the Service
import Restofire
class ViewController: UIViewController {
var person: [String: Any]!
var requestOp: RequestOperation<PersonGETService>!
func getPerson() {
requestOp = PersonGETService().response() {
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 Response = [String: Any]
let path: String = "get"
var parameters: Any?
init(parameters: Any?) {
self.parameters = parameters
}
}
Consuming the Service
import Restofire
class ViewController: UIViewController {
var person: [String: Any]!
var requestOp: RequestOperation<HTTPBinPersonGETService>!
func getPerson() {
requestOp = HTTPBinPersonGETService(parameters: ["name": "Rahul Katariya"]).response() {
if let value = $0.result.value {
self.person = value
}
}
}
deinit {
requestOp.cancel()
}
}
Request Level Configuration
import Restofire
import Alamofire
struct MoviesReviewGETService: Requestable {
var scheme: String = "http://"
var baseUrl: String = "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 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
}
}
License
Restofire is released under the MIT license. See LICENSE for details.