2015-07-21 65 views
0

在我的应用程序中,我有一个ViewController从用户获取数据,然后继承到TableViewController。我的TableViewController显示从REST调用获取的数据到远程服务器。从网络加载数据为TableViewController

我已编码在viewDidLoad中的http请求,并且在接收到数据时,我然后调用

self.tableView.reloadData() 

但它永远需要(5-10秒)的数据出现在TableView中,在REST呼叫完成之后。

我应该在其他地方放置我的REST呼叫吗?例如,在初始ViewController中执行所有数据检索,然后在所有数据准备好后再继续执行会更好吗?

我不认为我的代码是所有相关的,但这里是我的viewDidLoad里面的代码:

override func viewDidLoad() { 
    super.viewDidLoad() 

    self.tableView.contentInset = UIEdgeInsetsMake(20.0, 0.0, 0.0, 0.0) 

    // Uncomment the following line to preserve selection between presentations 
    // self.clearsSelectionOnViewWillAppear = false 

    // Display an Edit button in the navigation bar for this view controller. 
    self.navigationItem.rightBarButtonItem = self.editButtonItem() 

    DataManager.spSearch { (teamsJson) -> Void in 
     let json = JSON(data: teamsJson) 
     //println(json) 

     if let teamArray = json["d"]["query"]["PrimaryQueryResult"]["RelevantResults"]["Table"]["Rows"]["results"].array { 
      for teamDict in teamArray { 
       //println(teamDict) 
       if let teamCells = teamDict["Cells"]["results"].array { 
        var teamTitle: String = "" 
        var teamUrl: String = "" 
        for teamCell in teamCells { 
         // Each cell contains the value of a specific managed metadata 
         // validate if we are on the right one 
         if teamCell["Key"].string == "Title" { 
          println("Title=" + teamCell["Value"].string!) 
          teamTitle = teamCell["Value"].string! 
         } 
         if teamCell["Key"].string == "SPWebUrl" { 
          println("SPWebUrl=" + teamCell["Value"].string!) 
          teamUrl = teamCell["Value"].string! 
          let tenantLength = count(globalTenant) 
          // Remove the string containing the tenant frmo the beginning 
          teamUrl = suffix(teamUrl, count(teamUrl) - count(globalTenant)) 
         } 
        } 

        var team = Team(name: teamTitle, url: teamUrl) 
        self.teams.append(team) 
       } 
      } 
      println("Nb of teams= \(self.teams.count)") 
      self.tableView.reloadData() 
     } 
    } 

} 
+0

代码看起来没问题。我认为你在做其他事情,实际上需要5-10秒。 – ozgur

回答

1

看来你拨打reloadData在后台线程。试试这个:

NSOperationQueue.mainQueue().addOperationWithBlock { 
    self.tableView.reloadData() 
} 
+0

@pierrebo欢迎您:) – Bannings

+0

工程就像一个魅力,谢谢!您是否想解释为什么在主队列中运行它使其成为瞬时的,而不是后台线程?我在我的DataManager代码('UIApplication.sharedApplication()。networkActivityIndi​​catorVisible = true')中添加了一个网络指示器,它表明获取数据需要1-2秒。没有你的代码,它需要5-10秒。在tableview中显示,但你的代码使它无缝。 – pierrebo

+0

@pierrebo当然。 DataManager块在后台线程上执行。当你更新你的UI时,你应该在主线程上做到这一点。否则,你会看到这样的奇怪延迟。 – Bannings

相关问题