swift - 如何从json在 TableView 中显示 ImageView

标签 swift api web-services uitableview uiimageview

为了解析 json,我有以下函数

 func single_news(userid: Int) {

        var request = URLRequest(url: URL(string: news_url)!)
        request.httpMethod = "POST"

        //Pass your parameter here
        let postString = "userid=\(userid)"
        request.httpBody = postString.data(using: .utf8)
        let task = URLSession.shared.dataTask(with: request) { data, response, error in

            guard let data = data, error == nil else {
                print("error=(error)")
                return
            }


            let json: Any?

            do
            {

                json = try JSONSerialization.jsonObject(with: data, options: [])
                print("abcnews")
                //here is your JSON
                print(json)
                let jsonValue : NSDictionary = json as! NSDictionary
                self.results = jsonValue.object(forKey: "data") as! [[String:String]]
                self.DiscoveryNewsTableView.delegate = self
                self.DiscoveryNewsTableView.dataSource = self
                self.DiscoveryNewsTableView.reloadData()

//                let _ = getData.shared.getDataForTableView(dict: json)
            }
            catch
            {
                return
            }

            guard let server_response = json as? NSDictionary else
            {
                return
            }
        }
        task.resume()
    } 

为了获取数据,创建了该类

class getData: NSObject {

    var descriptionn : String = ""
    var image : String = ""

//    static let shared = getData()

    func getDataForTableView(results: [[String:String]], index : Int){

        var productArray = [String:String]()
        productArray = results[index]

        descriptionn = productArray["description"]!
        image = productArray["images"]!
    }
}

在表格 View 中显示数据

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCell(withIdentifier: "discoveryNewscell") as! DiscoveryNewsTableViewCell

//        if results.count > 0{
            classObject.getDataForTableView(results: results, index: indexPath.row)
            cell.sneakerImageView.image=filteredsneakernews[indexPath.row].image
                   print("abc image"+classObject.image)
        cell.newsTitle.text = classObject.descriptionn
//        }
        return cell
    }

如何以字符串格式显示图像.Image(classObject.image) 如何在表格 View 上显示 ImageView ?您可以从此链接下载代码。 https://drive.google.com/file/d/1bVQsuSQINSa6YRwZe2QwEjPpU_m7S3b8/view?usp=sharing

最佳答案

您想要显示图像,但您只有该图像的 URL 而不是图像本身,因此您需要下载它,然后显示它。我有一个经常使用的类,它允许您简单地调用一行来下载并缓存图像,这样您就可以执行如下操作:

classObject.getDataForTableView(results: results, index: indexPath.row)
let image_url = filteredsneakernews[indexPath.row].image
cell.sneakerImageView.loadImageUsingCacheWithUrlString(urlString: image_url!)

为此,您必须复制下面的类并在单元格类中,例如,您需要将 imageView 类型从标准 UIImageView 更改为 CustomImageView:

let imageView: CustomImageView!

//

import UIKit

let imageCache = NSCache<NSString, UIImage>()

class CustomImageView: UIImageView {

    var imageUrlString: String?

    func loadImageUsingCacheWithUrlString(urlString: String) {

        imageUrlString = urlString

        if let cachedImage = imageCache.object(forKey: urlString as NSString) {
            self.image = cachedImage
            return
        }

        self.image = nil

        let url = URL(string: urlString)
        URLSession.shared.dataTask(with: url!, completionHandler: { (data, response, error) in

            if error != nil { return }

            DispatchQueue.main.async {

                if let downloadedImage = UIImage(data: data!) {

                    if self.imageUrlString == urlString {
                        if self.imageUrlString != "" {
                            self.image = downloadedImage
                        } else {
                            self.image = nil
                        }
                    }

                    imageCache.setObject(downloadedImage, forKey: urlString as NSString)
                }
            }

        }).resume()
    }
}

关于swift - 如何从json在 TableView 中显示 ImageView ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48053622/

相关文章:

ios - 如何让我的应用程序永久显示音量而不是铃声?

java - Android 代码帮助从列表末尾删除

web-services - WS 被认为是 Restful 要求

web-services - 在 j2me 中使用 WSDL 文件的 stub 文件

swift - 以下来自 RxSwift/RxCocoa 的示例代码做了什么?

swift - 如何知道 Optional Chaining 哪里坏了?

api - Google Analytics API v3 授权以允许访问我的数据

api - Telegram Bot API 错误代码(集成群组和 channel )

coldfusion - 在 ColdFusion 中使用重定向的 Web 服务

ios - 如何以编程方式快速使用 UIView 覆盖整个屏幕