简体   繁体   中英

Reload data tableView from JSON

I have a problem with reload data in tableView in my simple swift app for iOS.

If I for the first time enter the city name into the cityTextField and press the getDataButton, so the data displays correctly, but If I enter the new city name into cityTextField and press button, so data are still the same like for the first city .

ViewController

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!
}

You can reload tableview in "loadDataWether()" function.

Like,

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()
}

You are not instantiating your tableView delegate. Make sure you call self.weatherTableView.delegate = self inside viewDidLoad() .

Also, you should create a new arrDict every time you load your data. self.arrDict = [] .

In case the above ajustments dont work you should get some time debugging it. Make sure the second request is loading the data and, if so, your self.weatherTableView.reloadData() might not being called. You could try moving it to loadDataWeather() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM