从API获取图像

问题描述:

我想从api中获取图像,从而获得图像的url,我是否需要另一个API调用以从它们的url下载图像?如何抓取每个图像并将其附加到数组中并将其显示在我的收藏视图单元格中。我宣布这个类范围 var videoArray = [funnyVideos]()从API获取图像

Alamofire.request(_url).responseJSON { (response) in 

    print(response.result.value!) 
    if let dict = response.result.value as? Dictionary<String, AnyObject> { 
     if let result = dict["result"] as? Dictionary<String, AnyObject> { 
      if let data = result["data"] as? [Dictionary<String, AnyObject>] { 

       for obj in data { 
        let mainObj = funnyVideos() 
        mainObj.parseData(from: obj) 
        videoArray.append(mainObj) 
        // print (obj) 
       } 

       if let image1 = data[0]["image"] as? String {   
        print(image1) 
       } 

       self.collection.reloadData() 
      } 
     } 
    } 
    completed() 
} 

这个功能之外的另一个类:搞笑视频

func parseData(from: Dictionary<String, AnyObject>){ 
    if let name = from["title"] as? String{ 
     self._name = name.capitalized 
    } 
} 

本功能配置单元保存用于收集标签和ImageView的网点另一个类细胞。

func configureCell(_ funny : funnyVideos) { 
    self.funny = funny 
    nameLabel.text = self.funny.name.capitalized 
    // imageView.image = UIImage() 
} 

func collectionView(_ collectionView: UICollectionView, cellForItemAt  indexPath: IndexPath) -> UICollectionViewCell { 
    fun = videoArray[indexPath.row] 
    cell.configureCell(fun) 
} 

我在这里有什么选择来从UIImage容器中的url中抓取它们?和print(image1)打印图像的URL。

+0

修复代码格式 –

试试吧,

可以使用AlamofireImage下载图像,并设置为的CollectionView。

是的,你需要调用图像,从JSON获取网址,摆脱URL图像您可以使用 使用这样

FUNC的CollectionView(_的CollectionView:UICollectionView,cellForItemAt indexPath:IndexPath) - > UICollectionViewCell {

guard let identifier = cellIdentifier else{ 
     fatalError("Cell identifier not provided") 
    } 
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: identifier , 
                    for: indexPath) as UICollectionViewCell 

让IMAGEURL = arrayImage [indexPath.row]

cell.imageView.setImage(URL: “IMAGEURL”)

恢复单元

}

https://github.com/rs/SDWebImage https://github.com/onevcat/Kingfisher

是的,你必须使图像的URL另一个API调用。您可以使用AlamofireImage或sdwebimage库下载图像。

先用正常的Alamofire库打开Api并获取所有图像的链接并将它们保存为字典或数组。然后使用AlamofireImage或sdwebimage进行另一个API调用。

你应该尝试sdwebimage becauz很容易

你应该使用一个名为Kingfisher 它会处理缓存以及图像的下载,当你提供的URL的雨燕库。 这是入门的链接。 Cheat Sheet