简体   繁体   中英

GET works only once

I'm new to iOS programming, so my question might not be complicated but I'm still struggling to find the best solution. Any help will be highly appreciated!

I'm trying to send GET request every time the user opens the app. I wrote the function loadMenu() that collects the data from a json file on the server and populates the table in the app.

The problem is that if I update the json file, it's not reflected in the app. If feels like the loadMenu() part of the code is just ignored.

Here's my code:

import UIKit

class TableViewControllerNew: UITableViewController {

var names = [String]()
var mealDescription = [String]()
var price = [Double]()



override func viewDidLoad() {
    super.viewDidLoad()
    loadMenu()
}




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

// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    // #warning Incomplete implementation, return the number of sections
    return 1
}

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    // #warning Incomplete implementation, return the number of rows
    var new = NSUserDefaults.standardUserDefaults().objectForKey("names") as! [String]
    print("test: \(new.count)")
    return new.count
}

func loadMenu() {

    print("viewDidLoad works")

    // Send HTTP GET
    let myUrl = NSURL(string: "http://localhost/myPi/selection/wheyStationSelection.json");
    let request = NSMutableURLRequest(URL:myUrl!);
    request.HTTPMethod = "GET";

    NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: { (data:NSData?, response:NSURLResponse?, error:NSError?) -> Void in

        dispatch_async(dispatch_get_main_queue()) {

            do {
                let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments)

                if let meals = json["meals"] as? [[String: AnyObject]] {
                    for meal in meals {
                        if let name = meal["name"] as? String {
                            self.names.append(name)
                            //NSUserDefaults.standardUserDefaults().setObject(self.names, forKey: "test1") as! [String]
                            //var new = NSUserDefaults.standardUserDefaults().objectForKey("test1") as? [String]
                            //print(new)
                        }
                        if let mealDescription = meal["mealDescription"] as? String {
                            self.mealDescription.append(mealDescription)
                        }
                        if let price = meal["price"] as? Double {
                            self.price.append(price)

                        }
                    }
                }
            } catch {
                print("error serializing JSON: \(error)")
            }
            NSUserDefaults.standardUserDefaults().setObject(self.names, forKey: "test1") as! [String]
            //print(self.names)
            //print(self.mealDescription)
            //print(self.price)
        }
    }).resume()
}





override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cellIdenifier = "MealTableViewCell"
    let cell = tableView.dequeueReusableCellWithIdentifier(cellIdenifier, forIndexPath: indexPath) as! MealTableViewCell
    var new = NSUserDefaults.standardUserDefaults().objectForKey("names") as! [String]
    let name = new[indexPath.row]
    //print(name)

    cell.mealNameLabel.text = name

    return cell
}   

@david is right, if you place your loadMenu() method in viewDidAppear() it will be called each and every time your view appears. You can read more about the various lifecycle phases of a UIViewController here

One other thing. It is not clear to me whether your loadMenu() isn't called every time or whether you are just not seeing the updated content.

I can see that you are not reloading your table view when the JSON has been updated. Therefore your TableView don't know that any updates has occurred and will not render again and you won't see any updates.

Therefore, right after this line:

 NSUserDefaults.standardUserDefaults().setObject(self.names, forKey: "test1")

You should tell your tableView to reload itself like so:

tableView.reloadData()

So you have:

NSUserDefaults.standardUserDefaults().setObject(self.names, forKey: "test1")
tableView.reloadData()

That should cause all your "render the TableView" methods to be called again, but this time with the new data and you should see the updated content.

Hope this helps you.

如果在viewDidAppear(animated:)调用loadMenu()而不是viewDidLoad() ,则每次离开应用程序并重新打开它时都会调用它。

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