2017-02-09 4 views
1

데이터베이스에서 문자열 검색을 수행했으며 사용자가 검색 막대에서 세 번째 문자를 푸시 한 후 JSON을 반환 한 후 모든 결과를 배열에 추가합니다 그것은 테이블 뷰를 데이터로 채 웁니다.신속 검색 막대 - Alamofire 요청으로 테이블보기 업데이트하기

비록 제가 문제를 다루고 있습니다. 검색 할 때 mens에 대한 결과를 얻습니다. 결과가 tableview에 표시됩니다.

모든 텍스트를 삭제하면 여성이 좋지만 ... 일부 문자열 등을 삭제할 때 내부에 index out of range 오류가 발생합니다. tableview cellForRowAt. 나는 그것이 tableview가 추가 된 배열을 얻고 셀을 채울 시간이 없다는 것을 깨뜨린다고 생각한다.

내가 알아 내려고하는 것은 쿼리 나 reloadData()에서 시간 지연을 설정하지 않고 어떻게 작동하게 할 수 있는지입니다. 시간 지연을 원하지 않는 이유는 일부 사용자의 경우 느린 iPhone이있을 수도 있고 2 초의 지연이 있어도 충돌 할 수 있기 때문입니다.

이있는 tableView가 reloadData을 수행하는 동안 filteredData의 상태를 변경하는 것 같습니다 내 코드

class SearchViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate, UISearchControllerDelegate{ 

@IBOutlet weak var searchResultTable: UITableView! 
    let searchController = UISearchController(searchResultsController: nil) 

    var filteredData = [Products]() 

override func viewDidLoad() { 
     super.viewDidLoad() 


     self.navigationController?.isNavigationBarHidden = true 
     searchController.searchResultsUpdater = self 
     searchController.dimsBackgroundDuringPresentation = false 
     definesPresentationContext = true 
     searchResultTable.tableHeaderView = searchController.searchBar 

     searchController.searchBar.delegate = self 

    } 


func searchBarSearchButtonClicked(_ searchBar: UISearchBar) { 
     searchBar.resignFirstResponder() 
    } 


    func getSearch(completed: @escaping DownloadComplete, searchString: String) { 
     if filteredData.isEmpty == false { 
      filteredData.removeAll() 
     } 
     let parameters: Parameters = [ 
      "action" : "search", 
      "subaction" : "get", 
      "product_name" : searchString, 
      "limit" : "0,30" 
     ] 


     Alamofire.request(baseurl, method: .get, parameters: parameters).responseJSON { (responseData) -> Void in 
      if((responseData.result.value) != nil) { 
       let result = responseData.result 

       if let dict = result.value as? Dictionary<String, AnyObject>{ 
        if let list = dict["product_details"] as? [Dictionary<String, AnyObject>] { 

         for obj in list { 
          let manPerfumes = Products(productDict: obj) 
          self.filteredData.append(manPerfumes) 
         } 


        } 
       } 
       completed() 
      } 
     } 
    } 


func numberOfSections(in tableView: UITableView) -> Int { 

     return 1 

    } 
    func tableView(_ tableView: UITableView, 
        heightForRowAt indexPath: IndexPath) -> CGFloat { 
     return 170 
    } 

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

     return filteredData.count 
    } 

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

      let cell:iPhoneTableViewCell = tableView.dequeueReusableCell(withIdentifier: "iPhoneTableCell", for: indexPath) as! iPhoneTableViewCell 

      let prods = self.filteredData[indexPath.row] //HERE I GET THE ERROR 
      cell.configureCell(products: prods) 

      return cell 

    } 

} 

extension SearchViewController: UISearchResultsUpdating { 

    func updateSearchResults(for searchController: UISearchController) { 

     if (searchController.searchBar.text?.characters.count)! >= 3 { 
        self.getSearch(completed: { 
        self.searchResultTable.reloadData() 

        self.searchResultTable.setContentOffset(CGPoint.zero, animated: true) 
       }, searchString: searchController.searchBar.text!) 
     } else { 
      self.searchResultTable.reloadData() 
     } 


    } 
} 

답변

1

입니다. numberOfRowsForSection이 3을 반환하고 사용자가 삭제 키를 히트하면 배열 크기는 0이됩니다. cellForRow은 인덱스 0,1 또는 2를 요청할 때 예외를 throw합니다.