从Api Url下载图像,并使用Alamofire在swift中的集合视图中显示

时间:2016-06-23 11:13:49

标签: swift

我已经能够从Jpi格式的Api中获取url。但这个是图像网址。现在我怎样才能从url下载该图像并在集合视图中显示。我有

 override func viewDidLoad() {
    super.viewDidLoad()

    Alamofire.request(.GET, "http://\(platform).eposapi.co.uk/?app_id=\(apiID)&app_key=\(apikey)&request=&request=gallery", parameters: nil)
        .responseJSON { response in
            print(response.request)  // original URL request
            print(response.response) // URL response
            print(response.data)     // server data
            print(response.result)   // result of response serialization

            if let JSON = response.result.value {
                print("JSON: \(JSON)")

                   self.imageData = JSON as! Array<AnyObject>
                   print(self.imageData)
                   print("total number of images = \(self.imageData.count)")
                   for image in self.imageData{
                   print(image)
            }



    }

JSON中,所有图片网址都会出现。我能看到它。现在如何从该URL下载图像并在集合视图中显示。请告诉任何人我如何在这里申请。

我得到的图片网址是:

  

[http://chicoshorwich.com/img/14517241531454.jpg
        http://chicoshorwich.com/img/14517241944082.jpg,         http://chicoshorwich.com/img/14517273984235.jpg,        http://chicoshorwich.com/img/14517274885779.jpghttp://chicoshorwich.com/img/1451727556453.jpghttp://chicoshorwich.com/img/14614027267627.jpghttp://chicoshorwich.com/img/14517278515475.jpghttp://chicoshorwich.com/img/14614068518289.jpghttp://chicoshorwich.com/img/14616123258824.jpghttp://chicoshorwich.com/img/14614027528137.jpghttp://chicoshorwich.com/img/14517344227700.jpg,{{ 3}},http://chicoshorwich.com/img/1461402768681.jpghttp://chicoshorwich.com/img/14614028323203.jpghttp://chicoshorwich.com/img/14614029485351.jpghttp://chicoshorwich.com/img/14614029565341.jpg   总图像数量= 16

请告诉解决方案。

4 个答案:

答案 0 :(得分:1)

使用我的代码。根据您的数据,我认为这是您的答案。我在你的代码中编辑了一些东西。试试吧。

<强>码

         Alamofire.request(.GET, "http://\(platform).eposapi.co.uk/?app_id=\
        (apiID)&app_key=\(apikey)&request=&request=gallery", parameters: nil)
        .responseJSON { response in
                       print(response.request)  // original URL request
                       print(response.response) // URL response
                       // print(response.data)     // server data
                       print(response.result)   // result of response serialization

                    if let JSON = response.result.value {
                        print("JSON: \(JSON)")

                        self.imageData = JSON as! Array<String>
                        print(self.imageData)
                        print("total number of images = \(self.imageData.count)\n")
                        for image in self.imageData{
                        print(image)
                    }
                        dispatch_async(dispatch_get_main_queue()) {
                            self.GalleryCollectionView.reloadData()
                        }


                 }

现在创建一个名为“GalleryCollectionViewCell”的自定义Collectionviewcell并将其添加到“cellForItemAtIndexPath”方法

override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Gallerycell", forIndexPath: indexPath) as! GalleryCollectionViewCell


    let url = NSURL(string: imageData[indexPath.row])
    cell.galleryImageView.af_setImageWithURL(url!, placeholderImage: UIImage(named: "logo.png"), filter: nil,  imageTransition: .CrossDissolve(0.5), runImageTransitionIfCached: true, completion: nil)


return cell
}

在“占位符”上从资产中获取任何加载程序图像。我在这里使用logo.png。你可以拿走你的。

答案 1 :(得分:0)

您可以逐个调用所有图片网址

//define your dispatch queue

    private let downloadQueue = dispatch_queue_create("ru.downloadimage.downloadQueue", nil)

//Define also this
private var photos = [NSURL]()

// Add your URL here like this or you can do as per your choice
if let urls = jsonDictionary.valueForKeyPath("download data") as? [String] {
                for (i, url) in urls.enumerate() {
                    photos.append(NSURL(string: url)!)
                }
            }

这是此处下载图像块的代码

// Define the cache variable first 
private var cache = NSCache()



// MARK: - Private

    private func downloadPhoto(url: NSURL, completion: (url: NSURL, image: UIImage) -> Void) {
        dispatch_async(downloadQueue, { () -> Void in
            if let data = NSData(contentsOfURL: url) {
                if let image = UIImage(data: data) {
                    dispatch_async(dispatch_get_main_queue(), { () -> Void in
                        self.cache.setObject(image, forKey: url)
                        completion(url: url, image: image)
                    })
                }
            }
        })
    }

从像这样的集合视图中调用此函数

override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(cellIdentifier, forIndexPath: indexPath) as! PhotoCell
        let url = photos[indexPath.item]
        let image = cache.objectForKey(url) as? UIImage

        cell.imageView.backgroundColor = UIColor(white: 0.95, alpha: 1)
        cell.imageView.image = image

        if image == nil {
            downloadPhoto(url, completion: { (url, image) -> Void in
                let indexPath_ = collectionView.indexPathForCell(cell)
                if indexPath.isEqual(indexPath_) {
                    cell.imageView.image = image
                }
            })
        }

        return cell
    }

答案 2 :(得分:0)

如果您有imageURL,可以使用Alamofire轻松下载图像。

确保您已安装导入AlamofireImage pod并且

import AlamofireImage

    Alamofire.request(.GET, url) // url is string here.
                .responseImage { response in 
                    if let image = response.result.value {
                        // image is here. 
                    }else{
                        // check what happned.
                    }
            }

可以在https://github.com/Alamofire/AlamofireImage

找到更多信息

答案 3 :(得分:0)

在cellForItemAtIndexPath中编写Ccr代码,并从url数组中提供url。 Ccr代码是正确的。但是在某些情况下,上面的代码需要时间来更新UI。如果您使用的是AlamofireImage,则不要使用以下代码。

 yourCell.yourCell_ImageView.af_setImage(withURL: URL(string: imageUrl)!)