json - UITableView 不显示来自 URL 的图像

标签 json swift uitableview swift3

<分区>

我有这段代码应该显示来自 URLS 的图像。我认为一切都很好,因为当我打印图像和 images 的计数时,我得到了 7 张图像的数组。

请查看我的代码并纠正我做错的地方。

 import UIKit
 import SwiftyJSON
 import Haneke

 class  SlideViewController: UIViewController , UITableViewDelegate ,        UITableViewDataSource {

@IBOutlet weak var tableview : UITableView!

 var images = [String]()
    override func viewDidLoad() {
    super.viewDidLoad()

    tableview.delegate = self
    tableview.dataSource = self
    getJSON()

}


func numberOfSections(in tableView: UITableView) -> Int {
    return 0
}


func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
     return images.count
}



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

    let cell = tableView.dequeueReusableCell(withIdentifier: "imageCell", for: indexPath) as! ImageTableViewCell

    let remote = images[indexPath.row]

    let imageurl = URL(string: remote)
    cell.images.sd_setImage(with: imageurl)


    return cell
}

func getJSON() {

    let url =  "http://localhost:8000/api/hello"
    let myuel = URL(string: url)
    let resquest = NSMutableURLRequest(url: myuel!)

    resquest.httpMethod = "GET"


    let task = URLSession.shared.dataTask(with: resquest as URLRequest, completionHandler: { data,response,error in
        if error != nil{
            print(error!.localizedDescription)
            return
        }

        let json = JSON(data)

        self.images = json["pic"].arrayObject! as! [String]
        print(self.images.count)
        print(self.images)


        DispatchQueue.main.async {
            self.tableview.reloadData()
        }

    })
    task.resume()
     }


  }

最佳答案

确保从以下方法返回一个部分

func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

使用此扩展从 url 异步加载和查看图像

extension UIImageView {
    public func imageFromServerURL(urlString: String) {

        URLSession.shared.dataTask(with: NSURL(string: urlString)! as URL, completionHandler: { (data, response, error) -> Void in

            if error != nil {
                print(error)
                return
            }
            DispatchQueue.main.async(execute: { () -> Void in
                let image = UIImage(data: data!)
                self.image = image
            })

        }).resume()
    }}

像这样使用上面的扩展将图像加载到 imageView。

cell.imageview.imageFromServerURL(urlString: urlString)

关于json - UITableView 不显示来自 URL 的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43738837/

相关文章:

html - 如何在 Angular 7 中从 JSON 生成 HTML FORM

javascript - 如何正确处理 Unterminated string 异常?

arrays - 如何在 Swift 中将正确位置的元素插入到排序数组中?

ios - 第一个分组 TableView 部分标题未显示

json - 从 kinesis firehose 解析 json

ios - 相同的日期...但不同?也许时区困惑

string - 交换字符串大小写 - swift

ios - 将文本设置为 tableviewcell 时分隔线未正确显示

iphone - UITableViewCell 中的多种颜色

javascript - dataModel URL javascript 函数不填充网格