iOS聊天列表搜索功能求助:FIND API返回结果展示问题
Hey there! Let’s sort out how to properly handle the search results from your FIND API and display them in your UITableView. I’ve reviewed your code and found a few key areas that need tweaks to get this working as expected.
Key Issues in Current Code
Let’s start with the problems in your existing implementation:
- Incorrect
chatnull check: Your current code checksif (chattt != nil)to trigger the "Find Action", but according to your API response, we need to jump toChatCreatePagewhenchatisnull—so the condition is reversed. searchActivestate not updated: You never setsearchActive = trueafter a successful search, so the tableView doesn’t switch to showing the search result.- Invalid reload call: In
cellForRowAt, you haveself.chatlisttable.reloadData()afterreturn cell—this line will never execute, sincereturnexits the function immediately. - Missing tableView refresh: After fetching search results, you don’t tell the tableView to reload and show the new data.
- Variable naming issues: Swift doesn’t allow hyphens in variable names (like
search-text), which would cause a compile error—this should besearchText.
Step-by-Step Fixes
1. Fix Variable Naming
First, correct your text field outlet (this is a critical compile fix):
@IBOutlet weak var searchText: UITextField! // Replaced "search-text" with "searchText"
2. Update searchapicall() Logic
Rewrite the API response handling to correctly check for chat null status, update the searchActive flag, and refresh the tableView:
func searchapicall(){ guard let userId = searchText.text, !userId.isEmpty else { // Show alert if search field is empty let alert = UIAlertController(title: "Alert", message: "Please enter a unique ID", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "OK", style: .cancel)) present(alert, animated: true) return } idd = userId guard let acce = UserDefaults.standard.string(forKey: "access-tokenn") else { // Handle missing access token let alert = UIAlertController(title: "Error", message: "Access token not found", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "OK", style: .cancel)) present(alert, animated: true) return } let headers: HTTPHeaders = [ "Authorization": "Bearer \(acce)", "Content-Type": "application/X-Access-Token" ] let searchUrl = Constants.Chatlistsearch + userId Alamofire.request(searchUrl, method: .get, headers: headers).responseJSON { response in switch response.result { case .success(let value): let mainDictionary = value as! NSDictionary let dataDict = mainDictionary.value(forKey: "data") as! [String: Any] let chatDict = dataDict["chat"] as? [String: Any] if chatDict == nil { // Chat doesn't exist, navigate to ChatCreatePage guard let chatCreateVC = UIStoryboard(name: "Main", bundle: .main).instantiateViewController(withIdentifier: "ChatCreatePage") as? ChatCreatePage else { print("Failed to instantiate ChatCreatePage") return } // Pass the user data if needed chatCreateVC.userData = dataDict["user"] as? [String: Any] self.navigationController?.pushViewController(chatCreateVC, animated: true) } else { // Chat exists, store the user data and show in tableView self.chatt = dataDict["user"] as! [String: Any] self.searchActive = true self.chatlisttable.reloadData() // Refresh tableView to show search result } case .failure(let error): print("Search API Error: \(error.localizedDescription)") let alert = UIAlertController(title: "Error", message: "Failed to search for user", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "OK", style: .cancel)) self.present(alert, animated: true) } } }
3. Correct TableView Data Source Methods
Update the tableView methods to properly handle the searchActive state and display the search result correctly (including avatar image):
extension ChatlistViewController: UITableViewDataSource, UITableViewDelegate { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return searchActive ? 1 : pro.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = chatlisttable.dequeueReusableCell(withIdentifier: "ChatlistTableViewCell", for: indexPath) as! ChatlistTableViewCell if !searchActive { // Show regular chat list let dict = pro[indexPath.row] let recepient = dict["recipient"] as! [String: Any] let name = recepient["name"] as! String let uniqueId = recepient["unique_id"] as! String let avatarUrl = recepient["avatar"] as! String cell.namelbl.text = name cell.idlbl.text = uniqueId cell.imageView?.sd_setImage(with: URL(string: avatarUrl), placeholderImage: UIImage(named: "Mahi.png")) } else { // Show search result let name = chatt["name"] as! String let uniqueId = chatt["unique_id"] as! String let avatarUrl = chatt["avatar"] as! String cell.namelbl.text = name cell.idlbl.text = uniqueId cell.imageView?.sd_setImage(with: URL(string: avatarUrl), placeholderImage: UIImage(named: "Mahi.png")) } return cell } }
4. Add Search Cancel/Reset Logic
To let users go back to the regular chat list after searching, add a way to reset searchActive (e.g., when the search text is cleared):
extension ChatlistViewController: UITextFieldDelegate { func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() searchapicall() return true } func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { let newText = (textField.text as NSString?)?.replacingCharacters(in: range, with: string) ?? "" if newText.isEmpty { // Reset to regular chat list when search field is empty searchActive = false chatlisttable.reloadData() } return true } }
Additional Tips
- Optional Binding: Use
guard letand optional binding more often to force unwrap values safely (instead of using!which can cause crashes if the value is nil). - Type Safety: Replace
NSDictionarywith Swift’s native[String: Any]for better type safety and readability. - Error Handling: Add more robust error handling for cases like missing access tokens, invalid API responses, etc.
内容的提问来源于stack exchange,提问作者Swathi

