一起养成写作习气!这是我参与「日新计划 4 月更文应战」的第26天,点击检查活动概况。
- 本文首要介绍下
RxAlamofire
,Rx关于网络恳求的封装
1. Swift中网络结构概述
咱们在swift开发中,一般会对网络恳求进行封装,一般会运用Alamofire(相当于咱们OC中的AFNetWork)或许Moya/Moya,它是对咱们Alamofire的封装,运用Moya上的一张图来表达下他们的关系
关于这些结构的运用,网上都有,咱们基本上都是封装下,这里就不说明了。首要介绍下运用RxSwift
把咱们的网络恳求封装城序列。
2. 运用RxSwift封装原生恳求
咱们运用RxSwift对原生的恳求封装,咱们运用demo例子检查运用。
response
let url = URL(string: "http://www.douban.com/j/app/radio/channels")!
URLSession.shared.rx.response(request: URLRequest(url: url))
.subscribe(onNext: { (response,data) in
print("response:\(response) \n data:\(data)" )
}, onError: { (error) in
print("error:\(error)")
}, onCompleted: {
print("网络恳求完结")
}) {
print("毁掉咯")
}.disposed(by: self.disposeBag)
恳求成果
看下完结,首要是对原生的URL request
进行封装,处理返回的数据,错误信息,活跃状态。
data
URLSession.shared.rx.data(request: URLRequest(url: self.url))
.subscribe(onNext: { (data) in
print("data:\(data)" )
}, onError: { (error) in
print("error:\(error)")
}, onCompleted: {
print("网络恳求完结")
}) {
print("毁掉咯")
}.disposed(by: self.disposeBag)
恳求成果
看下完结,能够发现是对Response
的封装,将恳求成果进行map
转换为咱们Data类型。
json
持续看下json的封装
URLSession.shared.rx.json(request: URLRequest(url: self.url))
.subscribe(onNext: { (json) in
print(json)
}, onError: { (error) in
print("error:\(error)")
}, onCompleted: {
print("网络恳求完结")
}) {
print("毁掉咯")
}.disposed(by: self.disposeBag)
打印成果
看下完结
把咱们恳求的数据进行转换为json数据。能够发现它们的关系是json -> data -> response
.咱们在运用的进程运用response即可。
3. RxAlamofire的运用
当然咱们实际运用进程一般都是运用三方封装好的结构,很少运用原始的网络恳求,咱们需要做一些统一的处理。咱们看下RxAlamofire
的运用吧。
RxAlamofire.requestJSON(.get, url)
.debug()
.subscribe(onNext: { (r, json) in
if let dict = json as? [String: AnyObject] {
// let valDict = dict["rates"] as! Dictionary<String, AnyObject>
// print(dict)
print(">>>>>>>>>>>>>>>>>>>自己的打印>>>>>>>>>>>>>>>>>>>>>>")
print(dict)
}
}, onError: { (error) in
})
.disposed(by: disposeBag)
咱们相同恳求上面的链接,get
恳求,打印成果:
能够发现关于恳求,封装了打印的信息。持续看下完结
底层是对咱们Alamofire
进行DataRequest
- 简单的运用
{
let stringURL = ""
// MARK: With Alamofire engine
_ = json(.get, stringURL)
.observeOn(MainScheduler.instance)
.subscribe { print($0) }
_ = request(.get, stringURL)
.flatMap { request in
request.validate(statusCode: 200..<300)
.validate(contentType: ["text/json"])
.rx.json()
}
.observeOn(MainScheduler.instance)
.subscribe { print($0) }
// progress
_ = request(.get, stringURL)
.flatMap {
$0
.validate(statusCode: 200..<300)
.validate(contentType: ["text/json"])
.rx.progress()
}
.observeOn(MainScheduler.instance)
.subscribe { print($0) }
// just fire upload and display progress
if let urlRequest = try? urlRequest(.get, stringURL) {
_ = upload(Data(), urlRequest: urlRequest)
.flatMap {
$0
.validate(statusCode: 200..<300)
.validate(contentType: ["text/json"])
.rx.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 validatedRequest = request
.validate(statusCode: 200..<300)
.validate(contentType: ["text/json"])
let dataPart = validatedRequest
.rx.data()
.map { d -> Data? in d }
.startWith(nil as Data?)
let progressPart = validatedRequest.rx.progress()
return Observable.combineLatest(dataPart, progressPart) { ($0, $1) }
}
.observeOn(MainScheduler.instance)
.subscribe { print($0) }
// MARK: Alamofire manager
// same methods with any alamofire manager
let manager = Session.default
// simple case
_ = manager.rx.json(.get, stringURL)
.observeOn(MainScheduler.instance)
.subscribe { print($0) }
// NSURLHTTPResponse + JSON
_ = manager.rx.responseJSON(.get, stringURL)
.observeOn(MainScheduler.instance)
.subscribe { print($0) }
// NSURLHTTPResponse + String
_ = manager.rx.responseString(.get, stringURL)
.observeOn(MainScheduler.instance)
.subscribe { print($0) }
// NSURLHTTPResponse + Validation + String
_ = manager.rx.request(.get, stringURL)
.flatMap {
$0
.validate(statusCode: 200..<300)
.validate(contentType: ["text/json"])
.rx.string()
}
.observeOn(MainScheduler.instance)
.subscribe { print($0) }
// NSURLHTTPResponse + Validation + NSURLHTTPResponse + String
_ = manager.rx.request(.get, stringURL)
.flatMap {
$0
.validate(statusCode: 200..<300)
.validate(contentType: ["text/json"])
.rx.responseString()
}
.observeOn(MainScheduler.instance)
.subscribe { print($0) }
// NSURLHTTPResponse + Validation + NSURLHTTPResponse + String + Progress
_ = manager.rx.request(.get, stringURL)
.flatMap { request -> Observable<(String?, RxProgress)> in
let validatedRequest = request
.validate(statusCode: 200..<300)
.validate(contentType: ["text/something"])
let stringPart = validatedRequest
.rx.string()
.map { d -> String? in d }
.startWith(nil as String?)
let progressPart = validatedRequest.rx.progress()
return Observable.combineLatest(stringPart, progressPart) { ($0, $1) }
}
.observeOn(MainScheduler.instance)
.subscribe { print($0) }
}
这里列举了一些简单的运用
4. 总结
关于RxSwift在网络中的应用,就是把咱们网络的恳求
转换为可观察序列
,通过发送它的恳求成果和状态,做到链式呼应
。