我想创建 Pin 图的对象图,并在 Pin 图内包含图像。我有一个 Pin 类,它存储 map 注释(图钉)。在这个类中,我有一个 Image 类型的图像数组。我的目标是让每个引脚都有自己的基于该引脚的坐标点的图像集。 (这与核心数据无关。这是关于实现下面的 Image 类)。
基本上,我想创建一个类图像以将下载的图像放在那里并将其存储到选定的引脚。一旦我获得了该引脚的 21 个图像,我就不想重新下载该特定引脚的新图像,除非按下按钮来执行此操作。例如,如果为纽约时代广场选择了一个图钉,并且我获得了 21 张街上狗的图像,则该图像将被保存。如果我现在返回 map 选择不同的图钉,然后决定重新选择之前的纽约时代广场,我仍然会在街上看到同样的 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
}
我的图像类当前为空:
import UIKit
class Image {
}
当用户使用长按手势在 map 上放置图钉时,该图钉不会添加到图钉集中。仅当用户选择引脚时才会发生这种情况。看这段代码:
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")
}
}
选择引脚后,应用程序将转到下一个 View Controller 。在 viewWillAppear 内部,对 Flickr 进行网络调用以下载与所选图钉的纬度/经度坐标关联的图像。这些图像用于显示在 Collection View 中。
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 下载每个 pin 的 21 个图像(如果可用)并将其存储在该数组中。
我已经能够存储引脚了。谁能帮忙解决这个问题吗?
最佳答案
不确定问题是什么...但似乎您正确存储了图像集合。剩下的就是实现 Image 类。您可以在其中创建一个名为 photo 的属性,该属性具有 UIImage 类,然后在网络调用中实例化这些属性。这是您要找的吗?
关于ios - Swift - 如何保存相关 map 注释(图钉)的图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31816222/