我目前正在尝试学习Rx编程。我发现Moya很吸引人,并且一直在尝试实现一个简单的网络请求,然后将该请求映射到对象,然后使用这些对象填充tableView。
我一直在关注本教程:http : //www.thedroidsonroids.com/blog/ios/rxswift-examples-3-networking/
我相信我在使用过程中会获得成功的响应,.debug
并获得以下输出:
2016-04-09 13:29:30.398: MyApi.swift:37 (findRepository) -> subscribed
2016-04-09 13:29:30.400: MyApi.swift:35 (findRepository) -> subscribed
2016-04-09 13:29:32.633: MyApi.swift:35 (findRepository) -> Event Next(Status Code: 20..., Data Length: 5747)
2016-04-09 13:29:32.633: MyApi.swift:35 (findRepository) -> Event Completed
这是我正在使用的代码:
let provider: RxMoyaProvider<MyApi>
let repositoryName: Observable<String>
func trackIssues() -> Observable<[Train]> {
return repositoryName
.observeOn(MainScheduler.instance)
.flatMapLatest { name -> Observable<[Train]?> in
print("Name: \(name)")
return self.findRepository(name)
}.replaceNilWith([])
}
internal func findRepository(name: String) -> Observable<[Train]?> {
print("help")
return self.provider
.request(MyApi.Trains(name, "c76a46ce2b3d8685982b/raw/10e86080c3b1beedd46db47f5bb188cc74ce5c78/sample.json"))
.debug()
.mapArrayOptional(Train.self)
.debug()
}
这是我尝试映射的对象:
import Mapper
struct Train: Mappable {
let distance: String
let eta: String
init(map: Mapper) throws {
try distance = map.from("distance")
try eta = map.from("eta")
}
}
我已经查看了网络响应,并且想知道我是否首先需要抽象“火车”数据。我已经尝试通过不幸运地映射到以下对象来尝试此操作:
import Mapper
struct TrainsResponse: Mappable {
let trains: String
init(map: Mapper) throws {
try trains = map.from("trains")
}
}
请在此处找到示例json响应:http : //pastebin.com/Wvx8d5Lg
所以我想知道是否有人可以帮助我看看为什么我无法将响应变成对象。谢谢。
=======
我尝试过进行Pod更新,但仍然无法正常工作。这是我将其绑定到tableView的位置:
func setupRx() {
// First part of the puzzle, create our Provider
provider = RxMoyaProvider<MyApi>()
// Now we will setup our model
myApi = MyApi(provider: provider, repositoryName: userName)
// And bind issues to table view
// Here is where the magic happens, with only one binding
// we have filled up about 3 table view data source methods
myApi
.trackIssues()
.bindTo(tableView.rx_itemsWithCellFactory) { (tableView, row, item) in
let cell = tableView.dequeueReusableCellWithIdentifier("issueCell", forIndexPath: NSIndexPath(forRow: row, inSection: 0))
cell.textLabel?.text = "Hello"
print("Hello")
return cell
}
.addDisposableTo(disposeBag)
}
绑定到(我在其中设置单元格的位置)内部的代码永远不会被调用。另外,如果我在我的Train映射器类中放置了一个断点,那么它也永远不会被调用。
它不起作用的原因是从服务器检索的JSON返回字典,而不是数组。您要解析的数组在该词典的“ trains”键下。本教程中使用的Moya-ModelMapper也具有用于此用法的方法。您只需要keyPath:
在mapArrayOptional()
方法中传递第二个参数。
因此,对于你问题的答案是替代:
.mapArrayOptional(Train.self)
用
.mapArrayOptional(Train.self, keyPath: "trains")
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句