在我的选项卡栏视图中,我的 TableView 在启动时无法加载数据,但是当我点击离开并点击返回时数据会出现

In my Tab Bar View, my TableView cannot load data when launched but data would then appear when I click away and click back

我正在尝试从 reddit.com/.json 加载标题列表,但是我在 UIViewController 下的表格视图在启动时不会加载数据,屏幕会像这样空白: http://imgur.com/ucriMht

我必须单击“下载”选项卡,然后单击返回“当前子”选项卡,以便我的 TableView 正确加载 json 文件中的数据: http://imgur.com/TJyW65O

我还附上了这个问题中该选项卡的 ViewController 代码,看看是否有人能发现我哪里做错了。

import UIKit

class CurrentSubViewController: UIViewController,UITableViewDataSource,UITableViewDelegate,NSURLConnectionDelegate,UISearchBarDelegate {

    var manager:DataManager = DataManager()
    var localJson:JSON=JSON.nullJSON
    @IBOutlet var tableView : UITableView!
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        manager.startConnection()

        print("subredditview loaded")

        // Do any additional setup after loading the view.
    }


     func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
    {

        return manager.json["data"]["children"].count
    }
    // Row display. Implementers should *always* try to reuse cells by setting each cell's reuseIdentifier and querying for available reusable cells with dequeueReusableCellWithIdentifier:
    // Cell gets various attributes set automatically based on table (separators) and data source (accessory views, editing controls)

     func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
    {

        let cell = self.tableView?.dequeueReusableCellWithIdentifier("TitleCell",forIndexPath:indexPath) as UITableViewCell
        let row=indexPath.row
        print("got here /table view yeah")

        cell.textLabel?.text = manager.json["data"]["children"][row]["data"]["title"].stringValue
        cell.detailTextLabel?.text = manager.json["data"]["children"][row]["data"]["author_name"].stringValue

        /**if !json["data"]["children"][row]["data"]["thumbnail"].stringValue.isEmpty
        {
            let thumbnailPath=json["data"]["children"][row]["data"]["thumbnail"].stringValue
            let thumbnailURL:NSURL=NSURL(string: thumbnailPath)!
            let thumbnailData=NSData(contentsOfURL:thumbnailURL)
            let thumbnail=UIImage(data:thumbnailData!)
            cell.imageView?.image=thumbnail
        }**/
        return cell
    }

     func searchBarSearchButtonClicked(searchBar: UISearchBar) {
        manager.query="http://reddit.com/r/"+searchBar.text+"/.json"
        manager.data=NSMutableData()

        manager.startConnection()
        tableView?.reloadData()
    }

        /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}

解决此问题的一种方法是在以这种方式从服务器接收数据时启动 networkActivityIndi​​cator:

UIApplication.sharedApplication().networkActivityIndicatorVisible = true

之后,当收到数据时,您可以将网络 activity 设置为 false,当网络 activity 完成后,您可以这样重新加载 tableView:

if UIApplication.sharedApplication().networkActivityIndicatorVisible == false{
                dispatch_async(dispatch_get_main_queue(), { () -> Void in
                    self.tableView.reloadData()
                })
            }

你的代码将是这样的:

import UIKit

class CurrentSubViewController: UIViewController,UITableViewDataSource,UITableViewDelegate,NSURLConnectionDelegate,UISearchBarDelegate {

var manager:DataManager = DataManager()
var localJson:JSON=JSON.nullJSON
@IBOutlet var tableView : UITableView!
override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated)
}
override func viewDidLoad() {
    super.viewDidLoad()
    manager.startConnection()
    UIApplication.sharedApplication().networkActivityIndicatorVisible = true
    print("subredditview loaded")

    // Do any additional setup after loading the view.
}


 func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{

    return manager.json["data"]["children"].count
}
// Row display. Implementers should *always* try to reuse cells by setting each cell's reuseIdentifier and querying for available reusable cells with dequeueReusableCellWithIdentifier:
// Cell gets various attributes set automatically based on table (separators) and data source (accessory views, editing controls)

 func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{

    let cell = self.tableView?.dequeueReusableCellWithIdentifier("TitleCell",forIndexPath:indexPath) as UITableViewCell
    let row=indexPath.row
    print("got here /table view yeah")

    cell.textLabel?.text = manager.json["data"]["children"][row]["data"]["title"].stringValue
    cell.detailTextLabel?.text = manager.json["data"]["children"][row]["data"]["author_name"].stringValue

    /**if !json["data"]["children"][row]["data"]["thumbnail"].stringValue.isEmpty
    {
        let thumbnailPath=json["data"]["children"][row]["data"]["thumbnail"].stringValue
        let thumbnailURL:NSURL=NSURL(string: thumbnailPath)!
        let thumbnailData=NSData(contentsOfURL:thumbnailURL)
        let thumbnail=UIImage(data:thumbnailData!)
        cell.imageView?.image=thumbnail
    }**/
    return cell
}

 func searchBarSearchButtonClicked(searchBar: UISearchBar) {
    manager.query="http://reddit.com/r/"+searchBar.text+"/.json"
    manager.data=NSMutableData()

    manager.startConnection()
    tableView?.reloadData()

   UIApplication.sharedApplication().networkActivityIndicatorVisible == false
   if UIApplication.sharedApplication().networkActivityIndicatorVisible == false{
            dispatch_async(dispatch_get_main_queue(), { () -> Void in
                self.tableView.reloadData()
            })
        }
}

    /*
// MARK: - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    // Get the new view controller using segue.destinationViewController.
    // Pass the selected object to the new view controller.
}
*/

}

我没有测试它,但请告诉我它是否适合您。 试试这个可能对你有帮助。