从URL检索并显示多个图像

时间:2017-04-18 11:40:38

标签: swift xcode xcode8 alamofire alamofireimage

尝试使用Swift3,Alamofire和AlamofireImage。我试图在tableview中显示一些Instagram图像。我使用Alamofire检索了地方data.json文件,如下所示:

{
  "places" : [
    { "name" : "place1", "url" : "http://instagramImage1.jpg" },
    { "name" : "place2", "url" : "http://instagramImage2.jpg" },
    { "name" : "place3", "url" : "http://instagramImage3.jpg" },
  ]
}

我已设置PlaceTableViewCell UIImageView并将其附加到相应控制器的插座。

我还有PlaceTableViewController,其中包括:

var places = [Place]() //empty array to store places

viewDidLoad()方法中,我调用私有函数:

loadJson()

,功能如下:

private func loadJson() {
    Alamofire.request("https://example.com/data.json").responseJSON { response in
        if let JSON = response.result.value as? [String : Any],
            let places = JSON["places"] as? [[String : String]] {
            for place in places {
                //should I call loadImage() function here?
            }
        }
    }
}

我还有一个JSON文件中每个地方的模型:

import UIKit

class Place {

    var name: String
    var url: String

    init?(name: String, url: String) {
        self.name = name
        self.url = url     
    }

}

问题

我不知道从哪里开始。我想使用AlamofireImage(我已经包含在我的项目中)来下载每个图像,但我可以在某种循环中执行此操作吗?我还想在一个新的表格行中显示每个图像。任何建议和代码示例都将非常感激。

2 个答案:

答案 0 :(得分:1)

我建议不要在loadJSON中获取图片。

为什么?

  • 在初始请求中可能会有大量照片回来,用户甚至可能永远不会在应用程序中向下滚动到足以看到其中的一些。

  • 最重要的是,如果同时初始化太多请求,某些请求可能会在等待其他请求完成时超时。所以这可能不是最好的解决方案。

所以,现在来解决方案。仅下载用户试图查看的单元格的图像数据是有意义的。

TableView仅为此目的使用委托方法

optional func tableView(_ tableView: UITableView, 
        willDisplay cell: UITableViewCell, 
           forRowAt indexPath: IndexPath)

使用此方法加载图像。

extension ViewController: UITableViewDelegate {
   func tableView(_ tableView: UITableView, 
        willDisplay cell: UITableViewCell, 
           forRowAt indexPath: IndexPath) {

    let photoURL = places[indexPath.row].url

    // fetch this photo from web using URL

    // get the table view cell and update the image
     if let cell = self.tableView.cellForRow(at: indexPath) as UITableViewCell {
         cell.imageView.image = //fetchPhoto
     }   
    }
}

答案 1 :(得分:0)

您可以在tableview控制器中使用以下代码在单元格中填充图像。为此,您还需要在tableview中创建一个单元格或使用xib创建自定义单元格。我的代码用于从xib加载自定义单元格。

 //MARK:- TableView Delegate and DataSource
func tableView(_ tableView: UITableView, numberOfRowsInSection sectionIndex: Int) -> Int {
    return places.count
}

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return 200//or cell height you want
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
     var cell  = tableView.dequeueReusableCell(withIdentifier: "PlaceCell") as? PlaceCell
    if cell == nil {
        cell = (loadFromNibNamed(viewClass: PlaceCell.self) as! PlaceCell)
    }

    cell?.ivCategory.af_setImage(withURL: URL(string: places[indexPath.row].url)) 
    return cell!
}

另请注意,一旦收到来自api的回复,您将不得不重新加载tableview。