Restofire is a protocol oriented network abstraction layer in swift that is built on top of Alamofire to use services in a declartive way.
- 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
- iOS 8.0+ / Mac OS X 10.10+ / tvOS 9.0+ / watchOS 2.0+
- Xcode 8+
- Swift 3.1+
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 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
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)
]
)
If you prefer not to use either of the aforementioned dependency managers, you can integrate Restofire into your project manually.
- 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 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 the "Embedded 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.
- 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!
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
}
}
import Restofire
struct PersonGETService: Requestable {
typealias Model = [String: Any]
var path: String = "56c2cc70120000c12673f1b5"
}
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()
}
}
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
}
}
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
}
}
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()
}
}
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)
}
}
}
}
}
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
}
}
-
"Restofire is Awesome"
-
123456789
-
12345.6789
-
true
-
{}
-
["Restofire","is","Awesome"]
-
{ "id" : 12345, "name" : "Rahul Katariya" }
-
[ { "id" : 12345, "name" : "Rahul Katariya" }, { "id" : 12346, "name" : "Aar Kay" } ]
Restofire is released under the MIT license. See LICENSE for details.