【发布时间】:2016-07-02 20:54:42
【问题描述】:
我正在使用 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
}
【问题讨论】:
-
这个方法是做什么的? afterWeatherCreated(newWeather!)
-
@HarshalBhavsar 我可能不需要那种方法。但我仍然没有找到解决问题的方法。
-
你的网络请求是异步的,所以你需要在获取数据后重新加载你的tableView。您可以在
afterWeatherCreatedclosure 的代码中添加它。
标签: ios json uitableview alamofire