【问题标题】:Reload data tableView from JSON从 JSON 重新加载数据 tableView
【发布时间】:2015-12-11 12:43:58
【问题描述】:

在我的简单 iOS Swift 应用程序中,我在 tableView 中重新加载数据时遇到问题。

如果我是第一次在cityTextField中输入城市名称并按下getDataButton,那么数据显示正确,但是如果我在cityTextField中输入新的城市名称并按下按钮, 所以数据仍然和第一个城市一样

视图控制器

import UIKit

class ViewController: UIViewController,UITableViewDelegate {

var arrDict :NSMutableArray=[]

@IBOutlet weak var cityTextField: UITextField!
@IBOutlet weak var weatherTableView: UITableView!


@IBAction func getDataButton(sender: AnyObject) {

    weatherDataSource("http://api.openweathermap.org/data/2.5/forecast?q=" + cityTextField.text! + "&appid=<app id>")

}

override func viewDidLoad() {
    super.viewDidLoad()

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}


func weatherDataSource(urlString: String) {

    let urlUTF = urlString.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)

    let url = NSURL(string: urlUTF!)

        let query = NSURLSession.sharedSession().dataTaskWithURL(url!) { (data, response, error) in dispatch_async(dispatch_get_main_queue(), { ()
            self.loadDataWeather(data!)
            self.weatherTableView.reloadData()
            })
        }
        query.resume()
}


func loadDataWeather(dataPocasi: NSData){

    do {
        if let json = try NSJSONSerialization.JSONObjectWithData(dataPocasi, options: []) as? NSDictionary {
            print(json)

            for var i = 0 ; i < (json.valueForKey("list") as! NSArray).count ; i++
            {
                arrDict.addObject((json.valueForKey("list") as! NSArray) .objectAtIndex(i))
            }
        }

    } catch {
        print(error)
    }


}

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
    return arrDict.count
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
    var cell : TableViewCell! = tableView.dequeueReusableCellWithIdentifier("Cell") as! TableViewCell

    if(cell == nil)

    {
        cell = NSBundle.mainBundle().loadNibNamed("Cell", owner: self, options: nil)[0] as! TableViewCell;
    }
    let strTitle : NSNumber=arrDict[indexPath.row] .valueForKey("dt") as! NSNumber
    let epocTime = NSTimeInterval(strTitle)
    let myDate = NSDate(timeIntervalSince1970:  epocTime)
    let dateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "hh:mm"
    let dateString = dateFormatter.stringFromDate(myDate)
    cell.dayLabel.text=dateString

    let strDescription : NSDictionary=arrDict[indexPath.row] .objectForKey("main") as! NSDictionary
    if let bla = strDescription["temp"]{
        cell.tempLabel.text=bla.stringValue
    }
    return cell as TableViewCell
}

}

TableViewCell

import UIKit

class TableViewCell: UITableViewCell{
@IBOutlet weak var dayLabel: UILabel!
@IBOutlet weak var tempLabel: UILabel!
}

【问题讨论】:

  • 您是否考虑过在加载新数组之前清除数据源数组?
  • 是的,在 loadDataWeather 中尝试空 arrDict
  • 不,我没有。我想试试,但我不知道怎么做。我是编程爱好者。这只是大学的学期项目,这是我的第一个应用程序
  • 检查是否获取输入的新城市的任何数据。并逐行调试,了解数据源发生了变化,调用了reload table。
  • 我检查并调试了代码,发现您在代码中提到的 URL 得到了 HTML 响应。

标签: ios swift uitableview


【解决方案1】:

您没有实例化您的 tableView 委托。确保在viewDidLoad() 中调用self.weatherTableView.delegate = self

此外,您应该在每次加载数据时创建一个新的 arrDict。 self.arrDict = [].

如果上述调整不起作用,您应该花一些时间调试它。确保第二个请求正在加载数据,如果是这样,您的 self.weatherTableView.reloadData() 可能不会被调用。您可以尝试将其移至loadDataWeather()

【讨论】:

  • THX adolfosrs。我第一次没有正确使用你的建议。但现在一切都好。非常感谢匹配
  • 欢迎您。那么如何将我的答案设置为正确答案并投票呢? :)
【解决方案2】:

您可以在“loadDataWether()”函数中重新加载tableview。

喜欢,

func loadDataWeather(dataPocasi: NSData){

    do {
        if let json = try NSJSONSerialization.JSONObjectWithData(dataPocasi, options: []) as? NSDictionary {
            print(json)

            for var i = 0 ; i < (json.valueForKey("list") as! NSArray).count ; i++
            {
                arrDict.addObject((json.valueForKey("list") as! NSArray) .objectAtIndex(i))
            }
        }

    } catch {
        print(error)
    }

    self.weatherTableView.reloadData()
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-11
    • 1970-01-01
    • 2016-03-06
    • 2011-06-12
    相关资源
    最近更新 更多