如何在CollectionView中显示API中的图像

时间:2016-11-11 22:31:28

标签: ios swift uicollectionview alamofire swifty-json

因此,我需要来自JSON的解析图像并在CollectionView中显示它们。我使用了一些这样的框架:Alamofire,AlamofireImage,SwiftyJson。

My JSON is here:


    {
    "data" : [
        {
          "id" : "Un5PeP1wG99QI",
          "rating" : "g",
          "trending_datetime" : "2016-11-11 22:00:01",
          "import_datetime" : "2016-08-05 23:33:46",
          "bitly_gif_url" : "http:\/\/gph.is\/2aXBfTM",
          "url" : "http:\/\/giphy.com\/gifs\/muslim-american-Un5PeP1wG99QI",
          "content_url" : "",
          "type" : "gif",
          "source" : "http:\/\/www.buzzfeed.com\/regajha\/a-group-of-muslim-hipsters-made-a-video-thats-really-really",
          "source_tld" : "www.buzzfeed.com",
          "source_post_url" : "http:\/\/www.buzzfeed.com\/regajha\/a-group-of-muslim-hipsters-made-a-video-thats-really-really",
          "is_indexable" : 0,
          "slug" : "muslim-american-Un5PeP1wG99QI",
          "bitly_url" : "http:\/\/gph.is\/2aXBfTM",
          "username" : "",
          "images" : {
            "fixed_height_small" : {
              "height" : "100",
              "mp4_size" : "10981",
              "width" : "179",
              "size" : "139756",
              "mp4" : "http:\/\/media3.giphy.com\/media\/Un5PeP1wG99QI\/100.mp4",
              "webp" : "http:\/\/media3.giphy.com\/media\/Un5PeP1wG99QI\/100.webp",
              "webp_size" : "44776",
              "url" : "http:\/\/media3.giphy.com\/media\/Un5PeP1wG99QI\/100.gif"
            },
            "downsized_large" : {
              "size" : "799980",
              "url" : "http:\/\/media3.giphy.com\/media\/Un5PeP1wG99QI\/giphy.gif",
              "width" : "500",
              "height" : "280"
            },
            "looping" : {
              "mp4" : "http:\/\/media.giphy.com\/media\/Un5PeP1wG99QI\/giphy-loop.mp4"
            },
            "preview" : {
              "height" : "280",
              "mp4" : "http:\/\/media1.giphy.com\/media\/Un5PeP1wG99QI\/giphy-preview.mp4",
              "mp4_size" : "48074",
              "width" : "500"
            },
            "downsized_small" : {
              "height" : "280",
              "mp4" : "http:\/\/media1.giphy.com\/media\/Un5PeP1wG99QI\/giphy-downsized-small.mp4",
              "mp4_size" : "48074",
              "width" : "500"
            },
            "fixed_width" : {
              "height" : "112",
              "mp4_size" : "11866",
              "width" : "200",
              "size" : "170452",
              "mp4" : "http:\/\/media3.giphy.com\/media\/Un5PeP1wG99QI\/200w.mp4",
              "webp" : "http:\/\/media3.giphy.com\/media\/Un5PeP1wG99QI\/200w.webp",
              "webp_size" : "50438",
              "url" : "http:\/\/media3.giphy.com\/media\/Un5PeP1wG99QI\/200w.gif"
            }
      ]
    }


我的ViewController就在这里:


import UIKit
import Alamofire
import AlamofireImage
import SwiftyJSON

class MainViewController: UICollectionViewController {
    @IBOutlet var myCollectionView: UICollectionView!

    var imagesArray = [[String : AnyObject]]()

    override func viewDidLoad() {
        super.viewDidLoad()
        loadImages()
    }


    // MARK: Cell
    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return imagesArray.count
    }

    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ImageCell", for: indexPath) as! CollectionViewCell
        //let url = NSURL(string: imagesArray[indexPath.row])
        //cell.imageView.af_setImage(withURLRequest: url)
        return cell
    }

    func loadImages() {
        Alamofire.request("http://api.giphy.com/v1/gifs/trending?api_key=dc6zaTOxFJmzC").responseJSON {(responseData) -> Void in
            if ((responseData.result.value) != nil) {
                let responseJsonData = JSON(responseData.result.value!)
                print(responseJsonData)
                if let resData = responseJsonData["data"].arrayObject {
                    self.imagesArray = resData as! [[String : AnyObject]]
                }
                if self.imagesArray.count > 0 {
                    self.myCollectionView.reloadData()
                }
            }
        }
    }
}

我的CollectionViewCell


    import UIKit

    class CollectionViewCell: UICollectionViewCell {
        @IBOutlet weak var imageView: UIImageView!

    }

请帮帮我。谢谢!

2 个答案:

答案 0 :(得分:0)

您可以使用map函数迭代data数组中的每个对象,并从url数组下的fixed_height_small对象中提取images。 (假设您需要从url

中提取fixed_height_small

你的json字典在解析后喜欢这个:

["data": 
     [
        ["images": 
           ["fixed_height_small": 
                ["url": "http:\/\/media3.giphy.com\/media\/Un5PeP1wG99QI\/100.gif"]
           ]
        ]
     ]
]

示例代码:

func loadImages() {
        Alamofire.request("http://api.giphy.com/v1/gifs/trending?api_key=dc6zaTOxFJmzC")
            .responseJSON {(responseData) -> Void in
            if ((responseData.result.value) != nil) {
                let responseJsonData = JSON(responseData.result.value!)
                print(responseJsonData)
                self.imagesArray = responseJsonData["data"].arrayValue.map({
                    (item) -> NSURL in
                    NSURL(string: item["images"]["fixed_height_small"]["url"].stringValue)!
                })

                if self.imagesArray.count > 0 {
                    self.myCollectionView.reloadData()
                }
            }
        }
    }

答案 1 :(得分:0)

您可以使用iOSDevCenters+GIF.swift file

在imageview中加载网址

这是相同代码的示例代码:

let gifURL : String = "http://api.giphy.com/v1/gifs/trending?api_key=dc6zaTOxFJmzC"
let imgURL = UIImage.gifImageWithURL(gifURL)
let imgvwTemp = UIImageView(image: imageURL)
cell.imageView.image = imgvwTemp.image

希望它会对您有所帮助:)