2017-05-08 26 views
0

我被困在這個小問題上,我有一個tableviewcontroller,它也是searchresultcontroller。我得到正確的數據對每個api調用,但tableview不重新加載。我不知道爲什麼它不工作。任何幫助或領導將非常感激。Tableview不重裝數據

class MasterViewController: UITableViewController,UISearchResultsUpdating { 
    var request:DataRequest? 
    var peopleArr:[Peoples] = [] 

    // MARK: - View Setup 
    override func viewDidLoad() { 
     super.viewDidLoad() 
     self.title = "Search" 

     definesPresentationContext = true 
    } 

    override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { 
     return 50.0 
    } 
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { 
     if indexPath.section == 1 { 
      //   if searchController.searchBar.selectedScopeButtonIndex == 0 { 
      let profileVc = self.storyboard?.instantiateViewController(withIdentifier: "profileVc") as! ProfileController 
      profileVc.profileData = (peopleArr[indexPath.row].user_id, peopleArr[indexPath.row].user_id) 
      self.navigationController?.pushViewController(profileVc, animated: true) 
     } 
    } 
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
     return peopleArr.count 
    } 
    override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { 
     return tableView.dequeueReusableCell(withIdentifier: "headerPeopleSec") 
    } 

    override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { 
     return "People" 
    } 

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 

     let cell = tableView.dequeueReusableCell(withIdentifier: "FollowingsCell", for: indexPath) as! FollowingsCell 
     cell.textLabel?.text = "\(indexPath.row)" 
     let people: Peoples 
     people = peopleArr[indexPath.row] 

     if people.following == "1" { 
      cell.followBtn.isHidden = true 
     } 
     else{ 
      cell.followBtn.isHidden = false 
     } 
     cell.profile_thumb!.showImageWithURL(urlString: people.photo_url) 
     cell.addAction = { cell in 
      self.addFriendAction(indexPath: indexPath , user:people) 
     } 
     cell.profile_thumb.motionIdentifier = people.user_id 
     cell.username.text = people.user_name 
     return cell 
    } 
    func getPeopleList(searchString:String?) { 
     if let req = self.request { 
      req.cancel() 
     } 
     let peopleBag = [ 
      "auth_token": (MemberProfile.loggedUser?._auth_token())!, 
      "per_page": 30, 
      "page": 1, 
      "search_key": searchString ?? "" 
      ] as [String : Any] 
     NVActivityIndicatorPresenter.sharedInstance.startAnimating(activityData) 
     self.request = HelperClass().doGetRequestCustom(url: BASE_URL + SEARCH_PEOPLE, param:peopleBag, header: [:], completion: {(response,responseObject, error) in 

      if let resMsg = (responseObject?.message.resp_status) { 
       NVActivityIndicatorPresenter.sharedInstance.stopAnimating() 

       //    if let hasNext = responseObject?.message.paging_data.next_page_exist as? Bool { 
       //     self.hasNextPage = hasNext 
       //    } 
       let dictionary:[String: AnyObject]? = responseObject?.message.data as? [String:AnyObject] //["member_followings"] 

       if let dict:Array = dictionary?["member_profiles"] as? Array<[String:AnyObject]>{ 

        for dic in dict { 
         let friend = Peoples() 
         friend.photo_url = (dic["photo"] as? String) ?? "" 
         friend.user_name = ((dic["user"]?["username"])! as String) 
         friend.user_id = (dic["id"])! as! String 
         friend.following = (dic["is_following"])! as! String 
         self.peopleArr.append(friend) 
        } 
        self.tableView.reloadData() 
       } 
       else{ 
       } 
      } 
      else{ 
       NVActivityIndicatorPresenter.sharedInstance.stopAnimating() 
      } 

      NVActivityIndicatorPresenter.sharedInstance.stopAnimating() 
     }) 
    } 

    func addFriendAction(indexPath:IndexPath , user:Peoples) { 
     let followBag = [ 
      "auth_token": (MemberProfile.loggedUser?.auth_token)!, 
      "following_profile_id": user.user_id 
      ] as [String : Any] 
     NVActivityIndicatorPresenter.sharedInstance.startAnimating(activityData) 
     HelperClass().doPostRequest(url: BASE_URL+FOLLOW_MEMBER , param: followBag, completion: { (dataResponse,response,error) in 

      if (response != nil) && (response?.message.resp_status)! 
      { 
       NVActivityIndicatorPresenter.sharedInstance.stopAnimating() 
       let cell = self.tableView.cellForRow(at: indexPath) as! FollowingsCell 
       cell.followBtn.isHidden = true 
       user.following = "1" 
      } 
      else 
      { 
       if (response != nil){ 
        NVActivityIndicatorPresenter.sharedInstance.stopAnimating() 
        HelperClass.showAlertViewWithTitle(title: "Error", Text: (response?.message.message)!, controllerToShowOn: self) 
       } 
       else{ 
        NVActivityIndicatorPresenter.sharedInstance.stopAnimating() 
        HelperClass.showAlertViewWithTitle(title: "Error", Text: "Something went wrong. Please check your internet connection & try again later.", controllerToShowOn: self) 
       } 
       return 
      } 
     }) 
    } 
    func updateSearchResults(for searchController: UISearchController) { 
     if !(searchController.searchBar.text! == "") { 
      self.peopleArr.removeAll() 
      self.tableView.reloadData() 
      let searchBar = searchController.searchBar 
      self.getPeopleList(searchString: searchBar.text!) 
     } 
    } 
    } 
+0

你在你的主線程重新加載你的tableview嗎?正如我看到你正試圖重新加載它在異步。 – ridvankucuk

+0

我也嘗試過。沒有工作 – DaIOSGuy

+0

我想你可能在你的調用reloadData()後得到數據。如何編寫完成處理程序並僅在擁有所有數據時調用reloadData()? numberOfRowsInSection之前有 – mat

回答

0

你需要讓主線程上的重載電話:

... 
for dic in dict { 
    let friend = Peoples() 
    friend.photo_url = (dic["photo"] as? String) ?? "" 
    friend.user_name = ((dic["user"]?["username"])! as String) 
    friend.user_id = (dic["id"])! as! String 
    friend.following = (dic["is_following"])! as! String 
    self.peopleArr.append(friend) 
} 
dispatch_async(dispatch_get_main_queue(), {() -> Void in 
    self.tableView.reloadData() 
}) 
... 

所有的UI修改總是發生在主線程上。大多數時候你在一個完成處理程序中,你必須派遣到主要修改UI。

+0

它也沒有工作 – DaIOSGuy

+0

@DaIOSGuy好吧,讓我們看看其他的東西。您是否已經放置了斷點並逐步完成,以確保正確讀取數據並將其添加到數據源中? –

+0

@DaIOSGuy也爲什麼你要重新加載tableView之前和期間self.getPeopleList(searchString:searchBar.text!)調用?這是一個非常昂貴的操作,應該儘可能少地執行。 –

0

似乎在func updateSearchResults(for searchController: UISearchController)錯了。 您可以嘗試在此功能結束時移動self.tableView.reloadData()嗎? 看起來當reloadData被調用時,數組被清除,並且尚未填充新值。

+0

只是做到了。沒有工作 – DaIOSGuy