
[英]Loading images to UITableViewCell and rounding corners using Alamofire
[英]Loading images very slow using Alamofire
我正在将 JSON 数据从我的网站获取到带有图像视图的表格视图。 数据加载速度很快,只是图像加载速度很慢,并且表格视图没有响应。
这是我的cellForRowAt
代码:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let customCell = tableView.dequeueReusableCell(withIdentifier: TableViewCell.identifier, for: indexPath) as! TableViewCell
//let cell = tableView.dequeueReusableCell(withIdentifier: "myCell", for: indexPath)
let item = data[indexPath.row]
customCell.AdTitle?.text = item["title"].string
customCell.AdDate?.text = item["time"].string
if let imageUrl = item["document"].string {
AF.request("https://mysite.co/uploads/" + imageUrl).responseImage { response in
if case .success( _) = response.result {
let url = NSURL(string:("https://mysite.co/uploads/" + imageUrl))
let imagedata = NSData.init(contentsOf: url! as URL)
if imagedata != nil {
customCell.AdImage.image = UIImage(data:imagedata! as Data)
}
}
}
}
return customCell
}
您可以通过SDWebImage使用高级缓存系统简单地加载图像,如下所示:
let imageURL = URL(string: "youRemoteImageURL") //Image URL
yourImageView.sd_setImage(with: imageURL, placeholderImage: UIImage(named: "placeholder.png"))
您的 tableViewCell 将如下所示:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let customCell = tableView.dequeueReusableCell(withIdentifier: TableViewCell.identifier, for: indexPath) as! TableViewCell
let item = data[indexPath.row]
customCell.AdTitle?.text = item["title"].string
customCell.AdDate?.text = item["time"].string
let imageUrl = item["document"].string
let url = NSURL(string:("https://mysite.co/uploads/" + imageUrl))
customCell.AdImage.sd_setImage(with: url, placeholderImage: UIImage(named: "placeholder.png"))
return customCell
}
你的代码很好。 您必须在主线程中加载图像。 编辑后的代码如下。 请尝试并告诉我
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let customCell = tableView.dequeueReusableCell(withIdentifier: TableViewCell.identifier, for: indexPath) as! TableViewCell
//let cell = tableView.dequeueReusableCell(withIdentifier: "myCell", for: indexPath)
let item = data[indexPath.row]
customCell.AdTitle?.text = item["title"].string
customCell.AdDate?.text = item["time"].string
if let imageUrl = item["document"].string {
AF.request("https://mysite.co/uploads/" + imageUrl).responseImage { response in
if case .success( _) = response.result {
let url = NSURL(string:("https://mysite.co/uploads/" + imageUrl))
let imagedata = NSData.init(contentsOf: url! as URL)
if imagedata != nil {
DispatchQueue.main.async {
customCell.AdImage.image = UIImage(data:imagedata! as Data)
}
}
}
}
}
return customCell
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.