RxAlamofire 是一个围绕 Swift 中优雅的 HTTP 网络库 Alamofire 的 RxSwift 包装器。
将 RxSwift 封装在 Alamofire 周围使得处理网络请求成为一项更流畅和更愉快的任务。Alamofire 是一个非常强大的框架,而 RxSwift 增加了以简单有效的方式组合响应的能力。
一个基本用法是(以一个简单的货币转换器为例)
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!"
}
目前,该库具有以下扩展
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) }
有三种安装 RxAlamofire 的方法
只需添加到你项目的 Podfile
中
pod 'RxAlamofire'
将以下内容添加到 Cartfile
github "RxSwiftCommunity/RxAlamofire" ~> 6.1
创建一个 Package.swift
文件
// 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"])
]
)
要手动安装此扩展,你应该将 RxAlamofire/Source/RxAlamofire.swift
导入到你的项目中,以及 RxSwift 和 Alamofire。
RxAlamofire 需要 Swift 5.1 以及 Alamofire (5.4.1) 和 RxSwift (6.0.0) 的专用版本。
为了支持最新的 RxSwift 5.1,请使用 RxAlamofire 5.7.1。
为了支持最新的 Swift 5.0,请使用 RxAlamofire 5.1.0。
为了支持最新的 Swift 4.2,请使用 RxAlamofire 4.5.0。