我有一個UITablView
包含代表每個員工的單元數。如何過濾包含異步下載圖像的UITableviewcells - Swift
而且我有UISearchBar
來過濾員工列表,我將員工數據存儲爲具有多個屬性的員工對象,所以我正在過濾員工。
我無法過濾的是員工照片,因爲我沒有將其作爲員工對象中的屬性保存,所以我調用下載cellForRowAtIndexPath
中的圖像的功能,就是這樣我無法再使用該圖像。
我需要一種方法來保存圖像供以後使用。
這cellForRowAtIndexPath
代碼:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = self.tableView.dequeueReusableCell(withIdentifier: cellID, for: indexPath) as! employeeCell
if self.isSearching == true {
let emp = searchedEmployees[(indexPath as NSIndexPath).row]
cell.empName.text = emp.getFistName() + " " + emp.getLastName()
cell.empPosition.text = emp.getPosition()
cell.status.text=emp.getStatus()
let myurlstring=emp.getPhotoURL()!
let myurl = myurlstring.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)
cell.empPhoto.downloadImageFrom(link: myurl!, contentMode: UIViewContentMode.scaleAspectFit)
}
else{
let emp = employees[(indexPath as NSIndexPath).row]
cell.empName.text = emp.getFistName() + " " + emp.getLastName()
cell.empPosition.text = emp.getPosition()
cell.status.text=emp.getStatus()
let myurlstring=emp.getPhotoURL()!
let myurl = myurlstring.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)
cell.empPhoto.downloadImageFrom(link: myurl!, contentMode: UIViewContentMode.scaleAspectFit)
}
return cell
}
這被下載圖像功能:
extension UIImageView {
func downloadImageFrom(link:String, contentMode: UIViewContentMode){
URLSession.shared.dataTask(with: URL(string:link)!, completionHandler: {
(data, response, error) -> Void in
DispatchQueue.main.async {
self.contentMode = contentMode
if let data = data {
self.image = UIImage(data: data)
self.image = self.image?.circle
self.image = self.image?.rounded
}
}
}).resume()
}
}
這是searchBar
功能:
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
if self.searchBar.text!.isEmpty {
// set searching false
self.isSearching = false
// reload table view
self.tableView.reloadData()
}else{
// set searghing true
self.isSearching = true
// empty searching array
self.searchedEmployees.removeAll(keepingCapacity: false)
// find matching item and add it to the searcing array
for i in 0..<self.employees.count {
let firstName : String = self.employees[i].getFistName()
let lastName : String = self.employees[i].getLastName()
let fullName : String = self.employees[i].getFistName()+" "+self.employees[i].getLastName()
if firstName.lowercased().range(of: self.searchBar.text!.lowercased()) != nil || lastName.lowercased().range(of: self.searchBar.text!.lowercased()) != nil || fullName.lowercased().range(of: self.searchBar.text!.lowercased()) != nil{
self.searchedEmployees.append(self.employees[i])
}
}
self.tableView.reloadData()
}
}
我想我的方式獲取圖像是錯誤的,因爲在我的情況下,我需要保存圖像供以後使用,我也不是我找不到異步下載圖像的方式,然後加載它保存後它在數組或其他東西。
任何幫助?
您可以保存成功下載後,文檔目錄,保持路徑或最後圖像路徑的名稱(其他路徑對於所有文檔目錄都是相同的)。然後使用該屬性從文檔目錄中獲取圖像。那有意義嗎 ? – Janmenjaya