RxAlamofire
RxAlamofire 是围绕优雅的 Swift HTTP 网络通信的 RxSwift 封装 Alamofire。
入门
将 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 有三种方法
CocoaPods
仅需在项目的 Podfile
中添加即可
pod 'RxAlamofire'
Carthage
在 Cartfile
中添加以下内容
github "RxSwiftCommunity/RxAlamofire" ~> 6.1
Swift 包管理器
创建一个 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。