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

时间:2018-01-01 22:06:11

标签: 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"]!
    }
}

在表格视图中显示数据

    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

1 个答案:

答案 0 :(得分:0)

您想要显示图片,但您只有该图片的网址而不是图片本身,因此您需要下载该图片,然后再显示该图片。我有一个我使用很多的课程,你可以简单地拨打一行下载并缓存图片,这样你就可以做到这样的事情:

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()
    }
}