Swift 3 从 url 搜索表

标签 swift uitableview

我已经设置了一个表,通过从我的服务器请求 json 数据来填充该表。

我想在顶部实现一个搜索栏,它根据搜索文本框中的字符串过滤结果。

我已经使用文本框中的“编辑已更改”操作并在每次按下按键时调用“getdata()”函数来解决此问题。

我遇到的问题在较慢的互联网连接上尤其明显。

当用户输入名称时,代码会在执行每个字母的函数时重新加载表 5-6 次,从而出现延迟。这对于用户来说看起来很困惑。

我是否以正确的方式处理这个问题?有没有办法在每次按下按键时取消该函数之前的任何执行?

@IBAction func textUpdated(_ sender: Any) {
    if (textField.text != nil){
        getdata(searchString: textField.text!)
    }
}
override func viewDidLoad() {
    print(value)
    let nib = UINib(nibName: "vwTblCell2", bundle: nil)
    tableView.register(nib, forCellReuseIdentifier: "cell2")
}
override func viewDidAppear(_ animated: Bool) {
    getdata(searchString: "")
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return self.tableData.count
}
// 3
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell  {
    let cell2: TblCell2 = self.tableView.dequeueReusableCell(withIdentifier: "cell2") as! TblCell2
    cell2.nameLabel.text = "\(tableData[indexPath.row] as String)"+" "+"\(tableLastName[indexPath.row] as String)"
    cell2.companyLabel.text = tableCompany[indexPath.row]
    cell2.jobTitleLabel.text = tableJobTitle[indexPath.row]
    let url = URL(string: "https://www.****.co.uk/wellpleased/backend/profileimages/\(tableImage[indexPath.row])")
    DispatchQueue.global().async {
        cell2.userImage.isHidden = true
        let data = try? Data(contentsOf: url!) //make sure your image in this url does exist, otherwise unwrap in a if let check / try-catch
        DispatchQueue.main.async {
            if data != nil {
            cell2.userImage?.image = UIImage(data: data!)
                cell2.userImage.isHidden = false
            }
        }
    }
    return cell2
}
// 4
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    print("Row \(tableID[indexPath.row]) selected")
    userSelect = tableID[indexPath.row]
    DispatchQueue.main.async {
        self.performSegue(withIdentifier: "goSwipeScreen", sender: self)
    }
}
// 5
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return 90
}
func getdata(searchString: String){
    let defaults = UserDefaults()
    let userid = defaults.string(forKey: "id")
    let newSearchString = searchString.replacingOccurrences(of: " ", with: "%20")
    let url = NSURL(string: "https://www.asmserver.co.uk/wellpleased/backend/searchattendees.php?userid=\(userid!)&searchstring=\(newSearchString)&eventid=\(value as String)")
    let task = URLSession.shared.dataTask(with: url as! URL) { (data, response, error) -> Void in
        if let urlContent = data {
            do {
                if let jsonResult = try JSONSerialization.jsonObject(with: urlContent, options: []) as? [[String:AnyObject]] {
                    self.tableData.removeAll()
                    self.tableLastName.removeAll()
                    self.tableCompany.removeAll()
                    self.tableJobTitle.removeAll()
                    self.tableImage.removeAll()
                    self.tableID.removeAll()
                    var i = 0
                    while i < jsonResult.count {
                        self.tableData.append(jsonResult[i]["firstname"]! as! String)
                         self.tableLastName.append(jsonResult[i]["lastname"]! as! String)
                        self.tableCompany.append(jsonResult[i]["company"]! as! String)
                        self.tableJobTitle.append(jsonResult[i]["jobtitle"]! as! String)
                        self.tableImage.append(jsonResult[i]["image"]! as! String)
                        self.tableID.append(jsonResult[i]["userid"]! as! String)
                        i = i + 1
                    }
                }
            } catch {
                print("JSON serialization failed")
            }
        } else {
            print("ERROR FOUND HERE")
        }
        DispatchQueue.main.async(execute: { () -> Void in
            self.tableView.reloadData()
        })
        self.tableView.isUserInteractionEnabled = true
    }
    task.resume()
}

最佳答案

假设您的应用的初始状态显示所有可用行,则不要在服务器上进行过滤(通过为搜索字段中的每个更改发送新查询)。

按照描述使用 UISearchBar 和 UISearchController here以及在许多其他地方仅过滤本地数据。

关于Swift 3 从 url 搜索表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41288530/

相关文章:

objective-c - initWithNibName 到底做了什么?

swift - 使用左栏按钮在导航栏上滑动后退手势

arrays - 有没有更好的方法来比较两个排序的数组?

Swift:无法更改imageView框架,imageView位于 Storyboard中

ios - 我想获取 currentUser 的 userId 并将其作为 child 添加到他们所有 friend 的数据中 - 在 Firebase 中使用 Swift

ios - UITabIeView CustomCell 在滚动之前无法正常工作... swift

ios - 以编程方式激活 UISearchBar 阻止用户与其交互

ios - 按下导航栏的编辑按钮时,如何使 TableView Cell 中的 textField 可编辑?

ios - UITableViewCells 试图绘制的无效上下文

swift - 如何在 collectionView 中传递单元格的选定状态(Swift)