2014-08-29 89 views
3

我有JSON成功填寫我的UITableView,但JSON經常更新,所以我需要刷新的能力。我跟着THIS TUTORIAL實現了拉取刷新控制。在視覺上,它似乎是一切正常,但當我打電話tableView.reloadData()表不重新加載。但是,如果我離開ViewController並返回,表格會更新。 tableView.reloadData()爲什麼會在viewDidAppearviewWillAppear中工作,但不在我自定義的refresh()函數中?拉到刷新在Swift不重新加載UITableView

MainVC.swift文件

class MainVC: UIViewController, UITableViewDelegate, UITableViewDataSource { 

     @IBOutlet var tableView: UITableView! 
     var dataArray: NSArray = NSArray() 

     @IBOutlet var Controller: UISegmentedControl! 

     var refreshControl:UIRefreshControl! 

     func refresh(sender:AnyObject) 
     { 
      refreshBegin("Refresh", 
       refreshEnd: {(x:Int) ->() in 
        self.tableView .reloadData() 
        println("Table Reloaded") 
        self.refreshControl.endRefreshing() 
      }) 
     } 

     func refreshBegin(newtext:String, refreshEnd:(Int) ->()) { 
      dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { 
       println("refreshing") 
       sleep(2) 

       dispatch_async(dispatch_get_main_queue()) { 
        refreshEnd(0) 
       } 
      } 
     } 

     override func viewWillAppear(animated: Bool) { 
      self.tableView .reloadData() 
     } 

     override func viewDidLoad() { 
      super.viewDidLoad() 
      navigationItem.titleView = UIImageView(image: UIImage(named: "logojpg.jpg")) 
      startConnectionAt("http://www.domain.com/json.php") 


      refreshControl = UIRefreshControl() 
      refreshControl.backgroundColor = UIColor.orangeColor() 
      refreshControl.tintColor = UIColor.whiteColor() 
      refreshControl.attributedTitle = NSAttributedString(string: "Pull to Refresh") 
      refreshControl.addTarget(self, action: "refresh:", forControlEvents: UIControlEvents.ValueChanged) 
      tableView.addSubview(refreshControl) 

      } 

//MARK: JSON Loading 

    var data: NSMutableData = NSMutableData() 
    func startConnectionAt(urlPath: String){ 
     var url: NSURL = NSURL(string: urlPath) 
     var request: NSURLRequest = NSURLRequest(URL: url) 
     var connection: NSURLConnection = NSURLConnection(request: request, delegate: self, startImmediately: false) 
     connection.start() 
    } 

    func connection(connection: NSURLConnection!, didFailWithError error: NSError!) { 
     println("Connection failed.\(error.localizedDescription)") 
    } 

    func connection(connection: NSURLConnection, didRecieveResponse response: NSURLResponse) { 
     println("Recieved response") 
    } 

    func connection(didReceiveResponse: NSURLConnection!, didReceiveResponse response: NSURLResponse!) { 
     self.data = NSMutableData() 
    } 

    func connection(connection: NSURLConnection!, didReceiveData data: NSData!) { 
     self.data.appendData(data) 
    } 

    func connectionDidFinishLoading(connection: NSURLConnection!) { 
     var dataAsString: NSString = NSString(data: self.data, encoding: NSUTF8StringEncoding) 
     var err: NSError 
     var json: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary 
     var results: NSArray = json["needs"] as NSArray 
     self.dataArray = results 

     tableView.reloadData() 
     println("success") 
    } 

//End loading of JSON 

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

    func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int { 
     return self.dataArray.count; 
    } 

    func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! { 
     var cell:CustomCell = self.tableView.dequeueReusableCellWithIdentifier("cell") as CustomCell 

     var rowData: NSDictionary = dataArray[indexPath.row] as NSDictionary 
     var firstName=rowData["needFirstname"] as String 
     var descrip=rowData["needDescription"] as String 
     var poster=rowData["needPoster"] as String 
     var city=rowData["needCity"] as String 
     var state=rowData["needState"] as String 
     var country=rowData["needCountry"] as String 

     cell.needFirstName.text = firstName 
     cell.needDescription.text = descrip 
     cell.needDescription.numberOfLines = 0 
     cell.needPoster.text = poster 
     cell.needCity.text = city 
     cell.needState.text = state 
     cell.needCountry.text = country 

     return cell 
    } 


    @IBAction func Change(sender: AnyObject) { 

     if Controller.selectedSegmentIndex == 0 { 
      startConnectionAt("http://www.domain.com/localJSON.php") 
     } 
     else if Controller.selectedSegmentIndex == 1 { 
      startConnectionAt("http://www.domain.com/intlJSON.php") 
     } 

     self.tableView .reloadData() 

    } 

} 
+1

嘿大衛上運行表更新 - 我只是試圖複製一個沒有Web服務調用和我的工作的簡單示例。你在哪裏設置dataArray到一個新的NSArray? – andrewcbancroft 2014-08-29 16:52:53

+0

我將添加我的MainVC文件的其餘部分 – davidrayowens 2014-08-29 16:54:33

+0

若要回答你的問題安德魯,dataArray被推入到connectionDidFinishLoading函數中的新的NSArray「結果」 – davidrayowens 2014-08-29 17:26:46

回答

5

你最後的評論是正確的,在我的觀點。

在您拉refresh功能,你叫tableView.reloadData(),然而,reloadData()本身並沒有做任何重新填充數據源中的元素(在你的情況,dataArray)。它只是在調用時將表格視圖的數據源重新加載當前中的所有數據

所以,我的建議是構建你refresh功能,從而會發生以下情況:

  1. 啓動對Web服務的請求。
  2. 當響應返回時(即,執行connectionDidFinishLoading),解析JSON結果並將該結果分配給dataArray實例。你似乎已經在connectionDidFinishLoading中這樣做了,所以這只是將請求發送到您的Web服務的問題,我想。
  3. 調用tableView.reloadData()顯示自上次顯示tableView數據後添加的所有新元素。再次,你已經在connectionDidFinishLoading中這樣做了,所以#1是我認爲需要發生的主要事情。
4

參考https://stackoverflow.com/a/25957339

不知道,但也許是連接在不同的線程運行,如果是的話,你需要在主UI線程

// using Swift's trailing closure syntax: 
dispatch_async(dispatch_get_main_queue()) { 
    self.tableView.reloadData() 
} 
+0

在swift http:// stackoverflow中的mainThread中重新載入表。COM /問題/ 24126261 /快捷的替代到performselectoronmainthread/31853168#31853168 – 2015-08-06 10:46:58

+0

它需要一個parentesis :) dispatch_async(dispatch_get_main_queue()){ self.tableView.reloadData() } – 2015-08-31 00:59:50