GithubHelp home page GithubHelp logo

isabella232 / rxalamofire Goto Github PK

View Code? Open in Web Editor NEW

This project forked from rxswiftcommunity/rxalamofire

0.0 0.0 0.0 3.04 MB

RxSwift wrapper around the elegant HTTP networking in Swift Alamofire

License: MIT License

Shell 7.49% Ruby 2.92% Swift 89.58%

rxalamofire's Introduction

RxAlamofire

RxAlamofire is a RxSwift wrapper around the elegant HTTP networking in Swift Alamofire.

Create release Version License Platform Carthage compatible

Getting Started

Wrapping RxSwift around Alamofire makes working with network requests a smoother and nicer task. Alamofire is a very powerful framework and RxSwift add the ability to compose responses in a simple and effective way.

A basic usage is (considering a simple currency converter):

let formatter = NSNumberFormatter()
formatter.numberStyle = .currencyStyle
formatter.currencyCode = "USD"
if let fromValue = NSNumberFormatter().numberFromString(self.fromTextField.text!) {

RxAlamofire.requestJSON(.get, sourceStringURL)
                .debug()
                .subscribe(onNext: { [weak self] (r, json) in
                    if let dict = json as? [String: AnyObject] {
                        let valDict = dict["rates"] as! Dictionary<String, AnyObject>
                        if let conversionRate = valDict["USD"] as? Float {
                            self?.toTextField.text = formatter
                                .string(from: NSNumber(value: conversionRate * fromValue))
                        }
                    }
                    }, onError: { [weak self] (error) in
                        self?.displayError(error as NSError)
                })
                .disposed(by: disposeBag)

} else {
    self.toTextField.text = "Invalid Input!"
}

Example Usages

Currently, the library features the following extensions:

let stringURL = ""

// MARK: URLSession simple and fast
let session = URLSession.shared()

_ = session.rx
    .response(.get, stringURL)
    .observeOn(MainScheduler.instance)
    .subscribe { print($0) }

_ = session.rx
    .json(.get, stringURL)
    .observeOn(MainScheduler.instance)
    .subscribe { print($0) }

_ = session.rx
    .data(.get, stringURL)
    .observeOn(MainScheduler.instance)
    .subscribe { print($0) }

// MARK: With Alamofire engine

_ = json(.get, stringURL)
    .observeOn(MainScheduler.instance)
    .subscribe { print($0) }

// validation
_ = request(.get, stringURL)
    .validate(statusCode: 200..<300)
    .validate(contentType: ["application/json"])
    .responseJSON()
    .observeOn(MainScheduler.instance)
    .subscribe { print($0) }

// progress
_ = request(.get, stringURL)
    .progress()
    .observeOn(MainScheduler.instance)
    .subscribe { print($0) }

// just fire upload and display progress
_ = upload(Data(), urlRequest: try! RxAlamofire.urlRequest(.get, stringURL))
    .progress()
    .observeOn(MainScheduler.instance)
    .subscribe { print($0) }

// progress and final result
// uploading files with progress showing is processing intensive operation anyway, so
// this doesn't add much overhead
_ = request(.get, stringURL)
    .flatMap { request -> Observable<(Data?, RxProgress)> in
        let dataPart = request.rx
            .data()
            .map { d -> Data? in d }
            .startWith(nil as Data?)
        let progressPart = request.rx.progress()
        return Observable.combineLatest(dataPart, progressPart) { ($0, $1) }
    }
    .observeOn(MainScheduler.instance)
    .subscribe { print($0) }


// MARK: Alamofire Session
// same methods with any Alamofire Session

let session = Session.default

// simple case
_ = session.rx.json(.get, stringURL)
    .observeOn(MainScheduler.instance)
    .subscribe { print($0) }

// URLHTTPResponse + JSON
_ = session.rx.responseJSON(.get, stringURL)
    .observeOn(MainScheduler.instance)
    .subscribe { print($0) }

// URLHTTPResponse + String
_ = session.rx.responseString(.get, stringURL)
    .observeOn(MainScheduler.instance)
    .subscribe { print($0) }

// URLHTTPResponse + Validation + JSON
_ = session.rx.request(.get, stringURL)
    .validate(statusCode: 200 ..< 300)
    .validate(contentType: ["text/json"])
    .json()
    .observeOn(MainScheduler.instance)
    .subscribe { print($0) }

// URLHTTPResponse + Validation + URLHTTPResponse + JSON
_ = session.rx.request(.get, stringURL)
    .validate(statusCode: 200 ..< 300)
    .validate(contentType: ["text/json"])
    .responseJSON()
    .observeOn(MainScheduler.instance)
    .subscribe { print($0) }

// URLHTTPResponse + Validation + URLHTTPResponse + String + Progress
_ = session.rx.request(.get, stringURL)
    .validate(statusCode: 200 ..< 300)
    .validate(contentType: ["text/something"])
    .flatMap { request -> Observable<(String?, RxProgress)> in
        let stringPart = request.rx
            .string()
            .map { d -> String? in d }
            .startWith(nil as String?)
        let progressPart = request.rx.progress()
        return Observable.combineLatest(stringPart, progressPart) { ($0, $1) }
    }
    .observeOn(MainScheduler.instance)
    .subscribe { print($0) }

// Interceptor + URLHTTPResponse + Validation + JSON
let adapter = // Some RequestAdapter
let retrier = // Some RequestRetrier
let interceptor = Interceptor(adapter: adapter, retrier: retrier)
_ = session.rx.request(.get, stringURL)
    .validate()
    .validate(contentType: ["text/json"])
    .responseJSON()
    .observeOn(MainScheduler.instance)
    .subscribe { print($0) }

Installation

There are three ways to install RxAlamofire

CocoaPods

Just add to your project's Podfile:

pod 'RxAlamofire'

Carthage

Add following to Cartfile:

github "RxSwiftCommunity/RxAlamofire" ~> 6.1

Swift Package manager

Create a Package.swift file

// swift-tools-version:5.0

import PackageDescription

let package = Package(
        name: "TestRxAlamofire",

        dependencies: [
            .package(url: "https://github.com/RxSwiftCommunity/RxAlamofire.git",
                     from: "6.1.0"),
        ],

        targets: [
            .target(
                    name: "TestRxAlamofire",
                    dependencies: ["RxAlamofire"])
        ]
)

Manually

To manual install this extension you should get the RxAlamofire/Source/RxAlamofire.swift imported into your project, alongside RxSwift and Alamofire.

Requirements

RxAlamofire requires Swift 5.1 and dedicated versions of Alamofire (5.4.1) and RxSwift (6.0.0).

For the last RxSwift 5.1 support, please use RxAlamofire 5.7.1.

For the last Swift 5.0 support, please use RxAlamofire 5.1.0.

For the last Swift 4.2 support, please use RxAlamofire 4.5.0.

rxalamofire's People

Contributors

bontojr avatar rynecheow avatar kzaher avatar freak4pc avatar sergdort avatar solidcell avatar bigmotor avatar luoxiu avatar nverinaud avatar carlosypunto avatar gaplo917 avatar lihao6485 avatar igrandav avatar sunshinejr avatar hamedmohammadi avatar idikic avatar george-gw avatar ashfurrow avatar balestrapatrick avatar orta avatar libec avatar zhouhao27 avatar 5d avatar wassimseif avatar vhbit avatar hamtiko avatar shams-ahmed avatar ufosky avatar mhmiles avatar marianpalkus 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.