如何在json的表视图中显示图像视图

问题描述 投票:0回答:1

要解析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"]!
    }
}

在表视图中显示数据

    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)如何在表格视图上显示图像视图?您可以从此链接下载代码.https://drive.google.com/file/d/1bVQsuSQINSa6YRwZe2QwEjPpU_m7S3b8/view?usp=sharing

swift api web-services uitableview uiimageview
1个回答
0
投票

您想要显示图像,但您只有该图像的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()
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.