我有一个应用程序,可以显示当前的天气。数据通过Alamofire从 forecast.io 下载。结果形成一个包含预测的表格。我使用了简单的tableviewdelegate和tableview数据源,一切正常。但是现在我想学习一些反应式的,使用rxswift和rxcocoa。经过一些谷歌搜索,以及来自raywanderlich的教程:我将代码更改为:
var week = Variable<[DailyWeather]>([])
override func viewDidLoad() {
super.viewDidLoad()
week.asObservable().subscribe { (e) in
self.generateTable()
}.addDisposableTo(disposeBag)
// tableView.delegate = self
// tableView.dataSource = self
tableView.backgroundColor = UIColor(red:0.81, green:0.81, blue:0.81, alpha:1)
refreshControl.tintColor = UIColor(red:1, green:1, blue:1, alpha:1)
self.tableView.addSubview(self.refreshControl)
manager.delegate = self
manager.requestWhenInUseAuthorization()
updateLocation()
}
func downloadData(_ completion: @escaping DownloadComplete) {
var weatherURL: String {
if pre == "ru" {
return("(BASE_URL)(API_KEY)/(latitudeNew),(longitudeNew)?units=si&lang=ru")
} else {
return("(BASE_URL)(API_KEY)/(latitudeNew),(longitudeNew)?units=si")
}
}
print(weatherURL)
if let url = URL(string: weatherURL) {
let request = Alamofire.request(url)
request.validate().responseJSON { response in
switch response.result {
case .success:
self.week.value = []
self.weekly = []
if let data = response.result.value as! [String: AnyObject]! {
self.weatherDict = data["currently"] as! [String: AnyObject]!
self.currentDict = CurrentWeather(weatherDictionary: self.weatherDict)
self.dailyArray = data["daily"]?["data"] as! [[String: AnyObject]]!
for dailyWeather in self.dailyArray {
let daily = DailyWeather(dailyWeatherDict: dailyWeather)
self.weekly.append(daily)
}
for x in 0...7 {
if x == 0 {
} else {
self.week.value.append(self.weekly[x])
}
}
completion()
}
case .failure(let error):
self.showAlert("You are offline", message: "Enable network connection and try again")
print("Alamofire error: (error)")
}
}
}
}
func generateTable() {
week.asObservable().bindTo(tableView.rx.items(cellIdentifier: "WeatherViewCell", cellType: WeatherViewCell.self)) { (index, weather, cell) in
cell.configureCell(daily: weather, index: index)
}.addDisposableTo(disposeBag)
}
但是我收到这个致命错误:
fatal error: Failure converting from Optional(<UIView: 0x7facad60f620; frame = (0 0; 414 736); autoresize = W+H; layer = <CALayer: 0x60800002e520>>) to UITableViewDataSource: file /Users/ruslansabirov/Desktop/swift/Havo4/Pods/RxCocoa/RxCocoa/RxCocoa.swift, line 146
(lldb)
请帮忙,我做错了什么?
检查表视图委托和数据源方法。如果在代码中设置了表视图委托,则必须在使用 RXSwift 时实现表视图的委托方法,否则应用程序崩溃。
你只需要调用func generateTable((一次。表视图将自动更新。因为它是数据绑定覆盖
func viewDidLoad() {
super.viewDidLoad()
self.generateTable()
tableView.backgroundColor = UIColor(red:0.81, green:0.81, blue:0.81, alpha:1)
refreshControl.tintColor = UIColor(red:1, green:1, blue:1, alpha:1)
self.tableView.addSubview(self.refreshControl)
manager.delegate = self
manager.requestWhenInUseAuthorization()
updateLocation()
}