Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/106.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/image/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 来自赢得';t显示在我的收藏视图中_Ios_Image_Swift_Uiimage_Uicollectionview - Fatal编程技术网

Ios 来自赢得';t显示在我的收藏视图中

Ios 来自赢得';t显示在我的收藏视图中,ios,image,swift,uiimage,uicollectionview,Ios,Image,Swift,Uiimage,Uicollectionview,您可以在getData()函数中看到,我有一个for in循环,它在URL数组中循环,将这些URL更改为UIImages,并将其分配给名为photos的全局变量 // // ViewController.swift // Fashun // // Created by Alex Macleod on 20/10/14. // Copyright (c) 2014 Alex Macleod. All rights reserved.

您可以在getData()函数中看到,我有一个for in循环,它在URL数组中循环,将这些URL更改为UIImages,并将其分配给名为photos的全局变量

        //
    //  ViewController.swift
    //  Fashun
    //
    //  Created by Alex Macleod on 20/10/14.
    //  Copyright (c) 2014 Alex Macleod. All rights reserved.
    //

    import UIKit

    class ViewController: UIViewController, UICollectionViewDelegateFlowLayout, UICollectionViewDataSource {

        var collectionView: UICollectionView?

        var instanceOfCustomObject: CustomObject = CustomObject()
        var accessToken: NSString!
        var userDefaults: NSUserDefaults!

        // the range represents integer values 0, 1, and 2
        // the range now represents integer values 6, 7, and 8

        let colorWheel = ColorWheel()
        var photoCount: Int! = 0
        var photos: UIImage! = UIImage()

    //    private let api = "d4984c8cfa78689bd066d82bec820fd5"



        override func viewDidLoad() {
            super.viewDidLoad()

            userDefaults = NSUserDefaults.standardUserDefaults()
            self.accessToken = userDefaults!.objectForKey("accessToken") as NSString
            println(self.accessToken)

            //        instanceOfCustomObject.someProperty = "Hello World"
    //        var accessToken : NSString? = NSString(instanceOfCustomObject.accessToken)
    //        println(accessToken)
    //        instanceOfCustomObject.authorize()
    //        instanceOfCustomObject.simpleAuth()


            // Do any additional setup after loading the view, typically from a nib.
            let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
    //        layout.sectionInset = UIEdgeInsets(top: 20, left: 0, bottom: 0, right: 0)
            layout.itemSize = CGSize(width: 124, height: 124)
            layout.minimumInteritemSpacing = 1.0
            layout.minimumLineSpacing = 1.0
            collectionView = UICollectionView(frame: self.view.frame, collectionViewLayout: layout)
            collectionView!.dataSource = self
            collectionView!.delegate = self
            collectionView!.registerClass(Cell.self, forCellWithReuseIdentifier: "Cell")
            collectionView!.backgroundColor = UIColor.whiteColor()
            self.view.addSubview(collectionView!)

            getData()

        }

        func getData() -> Void {
            let baseUrl = NSURL(string:"https://api.instagram.com/v1/users/3/media/recent/?access_token=\(self.accessToken)")

            let forcastUrl = NSURL(string: "", relativeToURL: baseUrl)

            //        let data = NSData(contentsOfURL: forcastUrl)
            //        println(data)
            let sharedSession = NSURLSession.sharedSession()
            let downloadTask: NSURLSessionDownloadTask = sharedSession.downloadTaskWithURL(baseUrl, completionHandler: { (location: NSURL!, response: NSURLResponse!, error: NSError!) -> Void in


                //            var urlContents = NSString.stringWithContentsOfURL(location, encoding: NSUTF8StringEncoding, error: nil)
                //            println(urlContents)

                let dataObject = NSData(contentsOfURL: baseUrl)
                //            println(dataObject)
                if (error == nil) {
                    let responseDictionary: NSDictionary = NSJSONSerialization.JSONObjectWithData(dataObject, options: nil, error: nil) as NSDictionary

                    var currentResponse = responseDictionary.valueForKeyPath("data.images.standard_resolution.url") as NSArray
//                    println(currentResponse)

                    for url in currentResponse {
                        var urls: NSString = url as NSString
//                        println(images)
                        var photoUrls = NSURL.URLWithString(urls)

                        var err: NSError?
                        var imageData :NSData = NSData.dataWithContentsOfURL(photoUrls,options: NSDataReadingOptions.DataReadingMappedIfSafe, error: &err)
                        var photos = UIImage(data:imageData)
                    }


                    //                println(currentResponse)
                    //                self.currentResponse = currentResponse as NSArray
//                    self.photoCount = currentResponse.count as Int
//                    println(self.photoCount)

                    dispatch_async(dispatch_get_main_queue(), { () -> Void in
                        self.photoCount = currentResponse.count as Int!
                        self.collectionView!.reloadData()
                        //                    self.temperatureLabel.text = "\(currentWeather.temperature)"
                        //                    self.iconView.image = currentWeather.icon!
                        //                    self.currentTimeLabel.text = "At \(currentWeather.currentTime!) it is"
                        //                    self.humidityLabel.text = "\(currentWeather.humidity)"
                        //                    self.percipitationLabel.text = "\(currentWeather.precipProbability)"
                        //                    self.summeryLabel.text = "\(currentWeather.summary)"
                        //
                        //                    self.refreshActivityIndicator.stopAnimating()
                        //                    self.refreshActivityIndicator.hidden = true
                        //
                        //                    self.refreshButton.hidden = false
                    })

                } else {

                    let networkIssueController = UIAlertController(title: "Error", message: "I got 99 problems but a bitch ain't one", preferredStyle: .ActionSheet)
                    let okButton = UIAlertAction(title: "OK", style: .Default, handler: nil)
                    networkIssueController.addAction(okButton)
                    let cancelButton = UIAlertAction(title: "Cancel", style: .Cancel, handler: nil)
                    networkIssueController.addAction(cancelButton)

                    self.presentViewController(networkIssueController, animated: true, completion: nil)

                    dispatch_async(dispatch_get_main_queue(), { () -> Void in
                        //Stop refresh animation
                        //                    self.refreshActivityIndicator.stopAnimating()
                        //                    self.refreshActivityIndicator.hidden = true
                        //                    self.refreshButton.hidden = false

                    })

                }

            })

            downloadTask.resume()

        }
您可以看到,在这个collectionview函数中,我试图通过将my photos变量(my loops of URL now UIImages)分配给imageView单元格来显示图像。什么也没发生我只是在IOS模拟器上得到一个白色屏幕,但是我的打印语句打印出了我试图显示的所有图像


提前谢谢

解析来自API的响应时,需要将图像存储到NSMutableArray中。修改后的代码将类似于以下内容:

        func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
            let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as Cell
            println(photos)
//            cell.textLabel.text = "Text"
            cell.imageView.image = photos
//            cell.imageView.backgroundColor = colorWheel.randomColor()

            return cell
        }
    }
在for循环中,您将在其中分配接收到的图像数据

var photos = NSMutableArray()
collectionView(collectionView:UICollectionView,cellForItemAtIndexPath indexPath:NSIndexPath)->UICollectionViewCell
函数中,您将加载图像,如下所示:

photos.addObject(UIImage(data:imageData))
您的集合视图现在应该开始显示图像,但是,您还应该考虑加载每个图像所产生的延迟以及重新加载图像所需的时间。您应该考虑使用缓存类来缓存已经下载的图像,这样用户在刷新或重新加载应用程序时不必重新加载它们。


SAMCache是一个很好的缓存库,它可以按预期工作,您可以在这里找到它:。实现相当简单,切中要害。

您将图像分配给名为photos的局部变量,而不是实例变量,但更重要的是,您应该将检索到的图像存储到数组中,因为您不能假设刚刚加载的照片将是cellaforItemAtIndexPath中所需的照片
cell.imageView.image = photos.objectAtIndex(indexPath.row)