简体   繁体   English

GET只工作一次

[英]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. 我是iOS编程的新手,所以我的问题可能并不复杂,但我仍在努力寻找最佳解决方案。 Any help will be highly appreciated! 任何帮助将不胜感激!

I'm trying to send GET request every time the user opens the app. 每当用户打开应用程序时,我都尝试发送GET请求。 I wrote the function loadMenu() that collects the data from a json file on the server and populates the table in the app. 我编写了函数loadMenu(),该函数从服务器上的json文件收集数据并填充应用程序中的表。

The problem is that if I update the json file, it's not reflected in the app. 问题是,如果我更新json文件,则该文件未反映在应用程序中。 If feels like the loadMenu() part of the code is just ignored. 如果感觉只是代码的loadMenu()部分被忽略。

Here's my code: 这是我的代码:

import UIKit 导入UIKit

class TableViewControllerNew: UITableViewController { 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. @david是正确的,如果将loadMenu()方法放在viewDidAppear() ,则每次出现视图时都会调用该方法。 You can read more about the various lifecycle phases of a UIViewController here 您可以在此处详细了解UIViewController的各个生命周期阶段

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. 我不清楚是否每次都没有调用loadMenu()还是只是看不到更新的内容。

I can see that you are not reloading your table view when the JSON has been updated. 我可以看到更新JSON后您没有重新加载表格视图。 Therefore your TableView don't know that any updates has occurred and will not render again and you won't see any updates. 因此,您的TableView不知道已发生任何更新,并且不会再次呈现,并且您将看不到任何更新。

Therefore, right after this line: 因此,在此行之后:

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

You should tell your tableView to reload itself like so: 您应该告诉tableView重新加载自身,如下所示:

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. 这将导致再次调用所有“呈现TableView”方法,但是这次使用新数据,您应该看到更新的内容。

Hope this helps you. 希望这对您有所帮助。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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