Swift - 如何为相关的地图注释(引脚)保存图像?

时间:2015-08-04 18:04:24

标签: ios arrays image swift network-programming

我想在Pins内部创建Pins with Pins的对象图。我有一个类Pin,它存储地图注释(引脚)。在这个类中,我有一个Image类型的图像数组。我的目标是让每个引脚都根据该引脚的坐标点拥有自己的图像集。 (这不是关于Core Data。它是关于实现下面的Image类)。

基本上,我想创建一个类图像,将下载的图像放在那里,并将其存储到选定的引脚。一旦我有21个图像的引脚,我不想重新下载该特定引脚的新图像,除非按下按钮这样做。例如,如果为纽约时代广场选择了一个别针,我在街上得到21张狗的图像,这将被保存。如果我现在回到地图选择一个不同的别针然后决定从之前重新选择纽约时代广场,我仍然应该在街上看到相同的21张狗图像。只需点击一个按钮进行重新下载,新的图片就会取代街道上的21张狗的图片,知道这些坐标的Flickr是什么。

import Foundation
import UIKit
import MapKit

class Pin: Hashable {

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

         let latitude: Double
         let longitude: Double
         var images = [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
}

My Image类目前为空:

import UIKit

class Image {


}

当用户使用长按手势在地图上放置图钉时,此图钉不会添加到图钉组中。仅当用户选择引脚时才会发生这种情况。看到这段代码:

class MapViewController: UIViewController, MKMapViewDelegate, UIGestureRecognizerDelegate {

var pins = Set<Pin>()

func mapView(mapView: MKMapView!, didSelectAnnotationView view: MKAnnotationView!) {

    if editAndDoneButtonText.title == "Edit" {

        println("Pin Selected")

        /* Get lat/long coordinates of a pin by tapping on the it and update appDelegate variables.
           Will use this for networking call to get Flickr images and to populate data structure for storage.
        */
        var latFromPin = view.annotation.coordinate.latitude
        var latString = String(stringInterpolationSegment: latFromPin)
        appDelegate.LAT = latString

        var lonFromPin = view.annotation.coordinate.longitude
        var lonString = String(stringInterpolationSegment: lonFromPin)
        appDelegate.LON = lonString

        latCollectionView = latFromPin
        lonCollectionView = lonFromPin

        // 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 {
                println("SAME: pin.hashValue: \(pin.hashValue), select.hashValue: \(select.hashValue)")
                dispatch_async(dispatch_get_main_queue()) {
                    let storyBoard = UIStoryboard(name: "Main", bundle: nil)
                    let secondViewController = self.storyboard!.instantiateViewControllerWithIdentifier("CollectionViewControllerID") as! CollectionViewController
                    self.navigationController?.pushViewController(secondViewController, animated: true)
                }
            }
        }
    }

    // Remove pins from map by tapping on it
    if editAndDoneButtonText.title == "Done" {
        var annotationToRemove = view.annotation
        mapView.removeAnnotation(annotationToRemove)

        println("remove pin - didSelectAnnotationView")
    }
}

当选择一个引脚时,应用程序将转到下一个视图控制器。在viewWillAppear内部,对Flickr进行网络调用,以下载与所选引脚的纬度/经度坐标相关联的图像。这些图像用于显示在集合视图中。

class CollectionViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, MKMapViewDelegate {

let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
var arrayOfImages: [UIImage] = [] // Array from Flickr
var pin: Pin!

override func viewWillAppear(animated: Bool) {
    // Flickr
    // 2 - API Method Arguments
    let methodArguments = [
        "method": appDelegate.METHOD_NAME,
        "api_key": appDelegate.API_KEY,
        "extras": appDelegate.EXTRAS,
        "lat": appDelegate.LAT,
        "lon": appDelegate.LON,
        "format": appDelegate.DATA_FORMAT,
        "nojsoncallback": appDelegate.NO_JSON_CALLBACK
    ]

    // 3 - Initialize session and url
    let session = NSURLSession.sharedSession()
    let urlString = appDelegate.BASE_URL + appDelegate.escapedParameters(methodArguments)
    let url = NSURL(string: urlString)!
    let request = NSURLRequest(URL: url)

    // 4 - Initialize task for getting data
    let task = session.dataTaskWithRequest(request) { data, response, downloadError in
        if let error = downloadError {
            println("Could not complete the request \(error)")
        } else {
            // 5 - Success! Parse the data
            var parsingError: NSError? = nil
            let parsedResult: AnyObject! = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments, error: &parsingError) as! NSDictionary
            // println("parsedResult = \(parsedResult)")

            if let photosDictionary = parsedResult.valueForKey("photos") as? [String:AnyObject] {
                // println("photosDictionary = \(photosDictionary)")

                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!)
                            self.arrayOfImages.append(finalImage!) // Append to array outside of this closure
                            count += 1

                            println(self.arrayOfImages.count)
                        }
                    }
                    dispatch_async(dispatch_get_main_queue()) {
                    self.collectionView.reloadData()
                    }
                }
            }
        }
    }
    // 6 - Resume (execute) the task
    task.resume()
}

// Collection view......
}

目前我正在使用名为var arrayOfImages: [UIImage] = []的数组。网络呼叫从Flickr为每个引脚下载21个图像(如果可用)并将其存储在该阵列中。

我已经能够存放引脚了。任何人都可以帮忙吗?

1 个答案:

答案 0 :(得分:0)

不确定问题是什么......但似乎您正确地存储了一组图像。剩下的就是实现Image类。您可以在其中创建一个名为photo的属性,该属性具有UIImage类,然后在您的网络调用中实例化那些属性。那是你在找什么?