我正在使用UITableViewController显示来自Web服务的项目列表,这些项目包含图像,我使用AlamofireImage从图像中获取数据并将其显示在UITableViewCell中,如下所示:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "postsCell", for: indexPath) as! PostsCell
let imgUrl = URL(string:"http://example.com/uploads/" + (self.array[indexPath.row]["cover"] as! String))
cell.delegate = self
Alamofire.request(imgUrl!).responseImage { response in
DispatchQueue.main.async {
if let image = response.result.value {
cell.message?.text = (self.array[indexPath.row]["title"] as! String)
cell.subMessage?.text = (self.array[indexPath.row]["username"] as! String)
cell.profileImage?.image = image
}
}
}
return cell
}
这是我如何填充self.array
getPosts(username: self.username!) { result in
self.array = result
self.tableView.reloadData()
}
这是getPosts:
func getPosts(username: String, completionHandler:@escaping (_ result:Array<Dictionary<String, Any>>) -> Void)
{
var returnedResults = Array<Dictionary<String, Any>>()
APIController().getUsersPosts(username: username)
{
(result: Array<Dictionary<String, Any>>) in
DispatchQueue.main.async {
//Return our results
returnedResults = result
completionHandler(returnedResults)
}
}
}
这是我对我的api的呼叫
func getPosts(username: String, completion: @escaping (_ result: Array<Dictionary<String, Any>>) -> Void)
{
let parameters: Parameters = [
"username": username
]
Alamofire.request(webservice + "?action=posts", method: HTTPMethod.post, parameters: parameters, encoding: URLEncoding.httpBody, headers: [:]).responseJSON { response in
if(response.error == nil)
{
if let result = response.result.value {
let jsonData = result as! Array<Dictionary<String, Any>>
completion(jsonData)
}
}
}
}
我的问题是,有没有一种更好,更有效的方法来显示URL中的图像?
答案 0 :(得分:2)
您可以使用SDWebImage
来维护应用程序的图像缓存,
您可以通过以下方式使用它:
import SDWebImage
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "postsCell", for: indexPath) as! PostsCell
let imgUrl = URL(string:"http://example.com/uploads/" + (self.array[indexPath.row]["cover"] as! String))
cell.profileImage.sd_setImage(with: imgUrl, placeholderImage: UIImage(named: "placeholder.png"))
// REST OF YOUR CODE TO FILL OTHE DATA OF YOUR CELL
return cell
}
您可以参考下面的git链接以获取更多信息: https://github.com/rs/SDWebImage
答案 1 :(得分:0)
无需编写responseImage
完成处理程序,您可以执行以下操作:
cell.profileImage?.af_setImage(withURL: imgUrl)