-
刷新状态(枚举)
public enum RefreshStatus: Int {
case DropDownSuccess // 下拉成功
case PullSuccessHasMoreData // 上拉,还有更多数据
case PullSuccessNoMoreData // 上拉,没有更多数据
case InvalidData // 无效的数据
}
-
创建ViewModel类,http请求类是一个对Alamofire的封装
class SchNoticeViewModel: SLViewModel {
static let shareInstance = SchNoticeViewModel()
var top = 10
var page = 1, t = 9
//数据获取
func getData() {
ALTools().rx_RequestXML(schNoticeApi.getData(page: self.page, top: self.top, uid: User.info.userID, schID: User.info.schID!, t: self.t)).subscribe(onNext: { (data) in
//SwiftJSON
let json = JSON(data: data)
let realm = try! Realm()
if self.page == 1 {
//第一页,下拉刷新的时候需要删除本地的所有数据
try! realm.write {
let objc = realm.objects(SchNoticeModel.self)
realm.delete(objc)
}
}
for mjson in json.arrayValue {
let model = SchNoticeModel()
....
//json解析,realm保存
try! realm.write {
realm.add(model, update: true)
}
}
if self.page == 1 {
self.refreshStatus.value = .DropDownSuccess
return
}
self.refreshStatus.value = json.count < top ? .PullSuccessNoMoreData:.PullSuccessHasMoreData
}).addDisposableTo(disposeBag)
}
}
-
控制器中
- 定义dataSource: var dataSource = Variable(SchNoticeModel)
- dataSource绑定到tableview
self.dataSource.asObservable().bind(to: self.tableView.rx.items(cellIdentifier: identifier, cellType: SchNoticeListTableViewCell.self)) { (row, model: SchNoticeModel, cell) in
cell.model = model
}.addDisposableTo(disposeBag)
* 刷新状态的绑定
```swift
SchNoticeViewModel.shareInstance.refreshStatus.asObservable().bind { (status) in
let objects = self.realm.objects(SchNoticeModel.self).sorted(byKeyPath: "time", ascending: false)
var array = [SchNoticeModel]()
for model in objects {
array.append(model)
}
self.dataSource.value = array
switch status {
case .DropDownSuccess:
self.tableView.mj_header.endRefreshing()
break
case .PullSuccessHasMoreData:
self.tableView.mj_footer.endRefreshing()
break
case .PullSuccessNoMoreData:
self.tableView.mj_footer.endRefreshingWithNoMoreData()
break
default:
break
}
}.addDisposableTo(disposeBag)
- 使用MJRefresh刷新,这里我对controller进行了封装,使用协议来实现刷新和加载更多
func tableViewRefresh(_ tableView: UITableView) {
//分页的页数
SchNoticeViewModel.shareInstance.page = self.page
//我们自己的数据接口的需求
SchNoticeViewModel.shareInstance.t = type
//获取数据
SchNoticeViewModel.shareInstance.getData()
总结: