ios - 如何将 url 数组发送到另一个 View 并转换为图像?

标签 ios arrays json swift networking

首先我需要解析 JSON 来获取 URL。使用这些 url,我将它们转换为图像以加载 UICollectionView。我需要发送一组 URL 来对另一个 View 执行相同的操作。问题是我需要将初始图像设置为我刚刚单击的缩略图,然后循环遍历数组以显示以下图像。这是我的代码,请帮忙!

 class HomepageCollectionViewController: UICollectionViewController {

    var imageCache = NSCache()

    var hingeImagesArray = [HingeImage]()
    var arrayToHoldConvertedUrlToUIImages = [UIImage]()
    var task: NSURLSessionDataTask?

   //full of urls
   var hingeImageUrls = [String]()




    override func viewDidLoad() {
        super.viewDidLoad()

        // Makes the network call for HingeImages
        refreshItems()


    }





    override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return 1
    }

    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return hingeImagesArray.count


    }

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

        let image = hingeImagesArray[indexPath.row]


        if let imageURL = image.imageUrl {

            if let url = NSURL(string: imageURL) {



                //Check for cached images and if found set them to cells - works if images go off screen
                if let myImage = imageCache.objectForKey(image.imageUrl!) as? UIImage {

                    cell.collectionViewImage.image = myImage

                }else {



                // Request images asynchronously so the collection view does not slow down/lag
                self.task = NSURLSession.sharedSession().dataTaskWithURL(url, completionHandler: { (data, response, error) -> Void in

//                    if (response as! NSHTTPURLResponse == 400) {
//                        print("400")
//                    }



                        // Check if there is data returned
                        guard let data = data else {
                            return
                        }

                        // Create an image object from our data and assign it to cell


                        if let hingeImage = UIImage(data: data){



                          //Cache images/set key for it
                          self.imageCache.setObject(hingeImage, forKey: image.imageUrl!)



                           dispatch_async(dispatch_get_main_queue(), { () -> Void in




                                cell.collectionViewImage.image = hingeImage




                             })
                        }

                })

                task?.resume()

               }
            }

        }

        return cell
    }
















    override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {

        if let cell = collectionView.cellForItemAtIndexPath(indexPath) {

            performSegueWithIdentifier("nextView", sender: cell)

        }else{
            print("no good")
        }
    }







    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {

        //Load imageView with the image clicked on
        //Must send over whole array with images to display in next screen



        if let indexPath = self.collectionView?.indexPathForCell(sender as! ImageCollectionViewCell) {

            if segue.identifier == "nextView" {

                let galleryViewController = segue.destinationViewController as! GalleryViewController


               //We are passing the url to the next screen then making another request to show them
               let imageUrl = hingeImagesArray[indexPath.row]


                //passesd a single image 
                galleryViewController.imageUrlFromOtherScreen = imageUrl.imageUrl


                //Pasing array of urls 
                galleryViewController.arrayOfImageUrlsFromOtherView = hingeImageUrls






               //let image = arrayToHoldConvertedUrlToUIImages[indexPath.row]

                //galleryViewController.selectedImageFromPreviousScreen = image

               // galleryViewController.arrayOfImageObjects = arrayToHoldConvertedUrlToUIImages

                //print(arrayToHoldConvertedUrlToUIImages)


            }


        }

    }





    //Execute JSON request
    func refreshItems() {

        HingeClient.executeJSONNetworkRequest { (hingeImages, error) in

            guard let images = hingeImages else {
                print("Error getting images with JSON")
                return
            }


            //Loop through array and append URLs to new array
            for moreImages in hingeImages! {

                self.hingeImageUrls.append(moreImages.imageUrl!)

            }



            self.hingeImagesArray = images



            self.collectionView?.reloadData()


        }
    }
















}

最佳答案

我现在可以看到您所做的是创建一个缓存对象,以根据其 URL 来缓存下载的图像。如果您想将 URL 数组传递到另一个 View ,一种可能性是将您的缓存共享为全局实例(例如单例对象)。这样从另一个角度来看,你只需检查缓存中是否存在该图像,然后从缓存中获取它,否则需要向服务器请求。

关于ios - 如何将 url 数组发送到另一个 View 并转换为图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36702959/

相关文章:

arrays - Bash:从另一个数组中删除一个数组中存在的项目

javascript - 如何将两个 AngularJS 应用程序合并为一个主应用程序的模块?

ios - IAP 恢复自定义交易

ios - 对于订阅系列中具有不同持续时间的自动续订订阅,Apple IAP 收据看起来如何?

C++ - 默认参数不能添加到类模板成员的外联定义中

ios - 如何在 Swift 中使用下标和上标?

arrays - Ruby - 转换多个数组以生成哈希

python - 手动将数组输入到python函数中

c# - 将数组的 JSON 数组反序列化为 c# 类

javascript - 如何在 REACT JS 中更新 onChange 事件的 JSON 对象状态?