简体   繁体   English

Swift-如何将图像保存到数组中并访问它们?

[英]Swift - How do I save images into an array and access them?

I have a map that allows me to add pins (annotations) to it. 我有一张地图,可以在其中添加图钉(注释)。 When I click on a pin, the app goes to another view controller and shows images downloaded from online. 当我单击图钉时,该应用程序将转到另一个视图控制器,并显示从在线下载的图像。 I "save" these images to an array but later I cannot access them. 我将这些图像“保存”到数组中,但后来无法访问它们。 For example, when I tap "Back" to go to the previous view controller and tap on the same pin from before, instead of showing the images I originally downloaded and saved, new images are downloaded from online. 例如,当我点击“返回”进入上一个视图控制器并从之前点击同一引脚时,不是显示我最初下载并保存的图像,而是从在线下载新图像。 Essentially, the images in the array are replaced. 本质上,替换阵列中的图像。 How can I save the images and retrieve them? 如何保存图像并检索它们? Sorry for long amounts of code, I shortened as much as I could. 对不起,很长的代码量,我尽可能地缩短了。

This is my class for the images: 这是我关于图像的课程:

class Image {

    var image: UIImage

    init(image: UIImage) {
        self.image = image
    }
}

This is my class for the pins. 这是我上课的针脚。 Notice, an array of type Image from the Image class is in here: 注意,来自Image类的Image类型的数组在这里:

class Pin: Hashable {

    var hashValue: Int {
        get {
            return "\(latitude.hashValue),\(longitude.hashValue)".hashValue
        }
    }

    let latitude: Double
    let longitude: Double
    var images = Array<Image>()

    init(latitude: Double, longitude: Double)
    {
        self.latitude = latitude
        self.longitude = longitude
    }
}

// must be declared in the global scope! and not just in the class scope
func ==(lhs: Pin, rhs: Pin) -> Bool
{
    return lhs.hashValue == rhs.hashValue
}

I add pins to a Set like so (no duplicates of pins allowed). 我将针脚添加到Set中是这样的(不允许重复的针脚)。 Also, the selected pin is sent to the secondViewController: 同样,将选定的引脚发送到secondViewController:

class MapViewController: UIViewController, MKMapViewDelegate, UIGestureRecognizerDelegate {

var pins = Set<Pin>()

func mapView(mapView: MKMapView!, didSelectAnnotationView view: MKAnnotationView!) {
 // Add pin to set
            let selectedCoordinatePoint = Pin(latitude: latFromPin, longitude: lonFromPin)
            var select = "\(latFromPin.hashValue),\(lonFromPin.hashValue)".hashValue
            pins.insert(selectedCoordinatePoint)

        //Goto to next view controller and show data depending on the pin selected
        for pin in pins {
            if pin.hashValue == select.hashValue {

                dispatch_async(dispatch_get_main_queue()) {
                    let storyBoard = UIStoryboard(name: "Main", bundle: nil)
                    let secondViewController = self.storyboard!.instantiateViewControllerWithIdentifier("CollectionViewControllerID") as! CollectionViewController

                    secondViewController.pin = pin

                    self.navigationController?.pushViewController(secondViewController, animated: true)
                }
            }
        }
    }
}

I download images from online and append to an array on this secondViewController (I shortened the code here): 我从网上下载图像,并将其追加到此secondViewController的数组中(在这里我缩短了代码):

class CollectionViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, MKMapViewDelegate {

    var pin: Pin!

    override func viewWillAppear(animated: Bool) {


                if let photosArray = photosDictionary["photo"] as? [[String:AnyObject]] {
                    // println("photosArray  =  \(photosArray )")

                    var count = 0
                    for photo in photosArray {
                        // 6 - Grab 21 random images
                        if count <= 20 {
                            // Grabs 1 image
                            let randomPhotoIndex = Int(arc4random_uniform(UInt32(photosArray.count)))
                            let photoDictionary = photosArray[randomPhotoIndex] as [String:AnyObject]

                            // 7 - Get the image url
                            let imageUrlString = photoDictionary["url_m"] as? String
                            let imageURL = NSURL(string: imageUrlString!)

                            // 8 - If an image exists at the url, append to array
                            let imageData = NSData(contentsOfURL: imageURL!)
                            let finalImage = UIImage(data: imageData!)
                            var image = Image(image: finalImage!)
                            self.pin.images.append(image)
                            count += 1

                            println(self.pin.images.count)
                        }
                    }
                }
            }
}

I'm not I understand what your asking exactly...you are making network calls to populate your image array. 我不明白您的确切要求是什么...您正在拨打网络电话以填充您的图像阵列。 If you just want to pass the image array from VC to VC, you can use prepareForSegue to pass the value. 如果只想将图像数组从VC传递到VC,则可以使用prepareForSegue传递值。

If you want to pull these down and then store them locally you need to read up on persistence. 如果您想将它们拉下来然后存储在本地,则需要阅读持久性。 For example you can use something like Core Data, Parse, Realm...I personally use Parse because of it's ease. 例如,您可以使用诸如Core Data,Parse,Realm之类的东西...我个人使用Parse是因为它很容易。 This is a good tutorial along the lines of what you're doing I think. 根据我的想法,这是一个很好的教程。 It uses Parse to store the image data: http://www.appcoda.com/instagram-app-parse-swift/ 它使用Parse存储图像数据: http : //www.appcoda.com/instagram-app-parse-swift/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM