我正在使用Alamofire解析JSON并在控制台上检索正确的JSON结果,但它没有出现在UITableView上。我认为这是竞争条件,但我不知道如何修复它。
WeatherViewController.swift
import Foundation
import UIKit
class WeatherViewController: UITableViewController{
var weatherStore: WeatherStore!
var weather: Weather!
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
print(weatherStore.allWeathers.count)
return weatherStore.allWeathers.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("UITableViewCell", forIndexPath: indexPath)
let weather = weatherStore.allWeathers[indexPath.row]
cell.textLabel?.text = String(weather.id)
cell.detailTextLabel?.text = weather.main
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
}
override func viewDidLoad() {
super.viewDidLoad()
weatherStore.createWeather { (fetchedWeather: Weather) in
self.weatherStore.allWeather.append(fetchedWeather)
}
tableView.reloadData()
let statusNarHeight = UIApplication.sharedApplication().statusBarFrame.height
let insets = UIEdgeInsets(top: statusNarHeight, left: 0, bottom: 0, right: 0)
tableView.contentInset = insets
tableView.scrollIndicatorInsets = insets
tableView.reloadData()
}
}
WeatherStore.swift
编辑:我评论过afterWeatherCreated(newWeather!)因为在Harshai评论后我发现我不需要它。
import Foundation
import Alamofire
class WeatherStore {
var allWeather = [Weather]()
func createWeather(afterWeatherCreated: (Weather) -> Void) {
var id: Int = 9
var main: String = ""
var newWeather: Weather?
Alamofire.request(.GET, "http://api.openweathermap.org/data/2.5/weather?xyz")
.responseJSON(completionHandler: { response in
if let JSON = response.result.value {
// id = JSON["id"] as! Int
//main = JSON["main"] as! String
let dataArray: NSArray = JSON["weather"] as! NSArray
for item in dataArray {
let obj = item as! NSDictionary
for (key, value) in obj {
if key.isEqual("id"){
id = value as! Int
}
if key.isEqual("main"){
main = value as! String
}
}
}
}
newWeather = Weather(id: id, main: main)
//afterWeatherCreated(newWeather!)
})
}
}
AppDeleage.swift
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
let weatherStore = WeatherStore()
let weatherController = window!.rootViewController as! WeatherViewController
weatherController.weatherStore = weatherStore
return true
}
答案 0 :(得分:0)
试试这个:
override func viewDidLoad() {
super.viewDidLoad()
weatherStore.createWeather { (fetchedWeather: Weather) in
self.weatherStore.allWeather.append(fetchedWeather)'
self.tableView.reloadData()
}
let statusNarHeight = UIApplication.sharedApplication().statusBarFrame.height
let insets = UIEdgeInsets(top: statusNarHeight, left: 0, bottom: 0, right: 0)
tableView.contentInset = insets
tableView.scrollIndicatorInsets = insets
tableView.reloadData()
}