[英]How to display JSON image on custom cell of tableview in Swift?
I'm new into coding, learning how to parse JSON image into table view able to display the labels but not able to display the image file. 我是新编码,学习如何将JSON图像解析为能够显示标签但不能显示图像文件的表格视图。 How to display it?
如何显示? I used the code given below please check it.
我使用下面给出的代码请检查。
import UIKit
class ViewController: UIViewController, UITableViewDelegate,UITableViewDataSource {
var dataArray = [[String:AnyObject]]()
@IBOutlet weak var myTable: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
let url = URL(string: "https://jsonplaceholder.typicode.com/photos")! //change the url
let session = URLSession.shared
var request = URLRequest(url: url)
request.httpMethod = "GET" //set http method as POST
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
let task = session.dataTask(with: request as URLRequest, completionHandler: { data, response, error in
guard error == nil else {
return
}
guard let data = data else {
return
}
do {
if let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [[String:Any]] {
self.dataArray = json as [[String : AnyObject]]
DispatchQueue.main.async {
self.myTable.reloadData()
}
print(json)
}
} catch let error {
print(error.localizedDescription)
}
})
task.resume()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataArray.count
}
func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
return 250
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 250
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "id") as! ModTableViewCell
cell.labout.text = String(describing: dataArray[indexPath.row]["id"]!)
cell.imagethum.image = UIImage(named :dataArray[indexPath.row]["thumbnailUrl"]! as! String)
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let vc = UIStoryboard.init(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier: "story") as? FinalViewController
var selectedindex = indexPath.row
vc?.jarray = dataArray
vc?.selectedindex1 = selectedindex
self.navigationController?.pushViewController(vc!, animated: true)
}
}
You need to download the image using thumbnailUrl
String
that you're getting from JSON
response. 您需要使用您从
JSON
响应获得的thumbnailUrl
String
下载图像。
Replace the implementation of cellForRowAt
method with the following code: 用以下代码替换
cellForRowAt
方法的实现:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "id") as! ModTableViewCell
cell.labout.text = String(describing: dataArray[indexPath.row]["id"] ?? "")
if let urlString = dataArray[indexPath.row]["thumbnailUrl"] as? String, let url = URL(string: urlString) {
URLSession.shared.dataTask(with: url) { (data, urlResponse, error) in
if let data = data {
cell.imagethum.image = UIImage(data: data)
}
}.resume()
}
return cell
}
Also, don't use forced unwrapping (!)
so extensively. 另外,不要如此广泛地使用
forced unwrapping (!)
。 It might result in crashing the app unnecessarily. 它可能会导致不必要地崩溃应用程序。
You need to download your image at first. 您需要先下载图像。 The basic solution is:
基本解决方案是:
if let url = URL(string: "YOUR_URL") {
if let data = try? Data(contentsOf: url) {
cell.imagethum.image = UIImage(data: data)
}
}
For more advanced solution take a look on SDWebImage framework ( for example ) - it's beginner-friendly. 有关更高级的解决方案,请查看SDWebImage框架(例如) - 它是初学者友好的。
We use this SDWebImage pod to load images from URL. 我们使用此SDWebImage窗格从URL加载图像。 This pod provides an async image downloader with cache support.
此pod提供具有缓存支持的异步映像下载程序。
Example Of SDWebImage as below SDWebImage示例如下
let img1 = savedInspofflineData[indexPath.row].image1
if img1 == ""{
//Error
}else{
let imageUrl = URL(string: img1!)!
cell.img1.sd_setImage(with: imageUrl, placeholderImage: UIImage(named: "logo_grey"), options: .refreshCached, completed: nil)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.