Tableview没有重新加载数据

Posted

技术标签:

【中文标题】Tableview没有重新加载数据【英文标题】:Tableview not reloading data 【发布时间】:2017-05-08 16:54:31 【问题描述】:

我被困在这个小问题上,我有一个 tableviewcontroller,它也是 searchresultcontroller。我正在针对每个 api 调用获取正确的数据,但 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!)
        
    
  

【问题讨论】:

您是否在主线程中重新加载您的表格视图?如我所见,您正在尝试以异步方式重新加载它。 我也试过了。没用 我认为您可能会在调用 reloadData() 后获取数据。编写完成处理程序并仅在拥有所有数据时调用 reloadData() 怎么样? 在 numberOfRowsInSection 之前我有所有数据。但是仍然没有调用 cellforRowAt 在这个 HelperClass().doGetRequestCustom helperClass 中你是在处理程序之前获取主线程吗? 【参考方案1】:

您需要在主线程上进行 reload 调用:

...
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 修改都必须在主线程上进行。大多数情况下,您都在完成处理程序中,您必须分派到 main 来修改 UI。

【讨论】:

@DaiosGuy 好的,让我们看看其他一些事情。您是否已放置断点并逐步执行以确保正确读取数据并将其添加到您的数据源? @DaIOSGuy 为什么还要在 self.getPeopleList(searchString: searchBar.text!) 调用之前和期间重新加载 tableView?这是一项非常昂贵的操作,应该尽可能少地执行。【参考方案2】:

func updateSearchResults(for searchController: UISearchController) 似乎有问题。 您可以尝试在此函数末尾移动self.tableView.reloadData() 吗? 似乎在调用 reloadData 时,数组已被清除,并且尚未填充新值。

【讨论】:

以上是关于Tableview没有重新加载数据的主要内容,如果未能解决你的问题,请参考以下文章

TableView reloadData 没有重新加载?

未在 TableView 中重新加载正确的数据

重新加载数据时 Tableview 崩溃

UITableview 没有重新加载

将数据从firebase加载到集合单元格内的tableview

在 tableView 中重新加载数据的问题