我正在创建一个应用,其中注释是通过地图上的长手势点击创建的,并保存在Core Data中。我已经检查了这个resource,但我仍然遇到地图上出现的注释问题。对我来说,Swift 2中的情况很好,不知道发生了什么变化以及我需要做些什么才能修复,因为它看起来对我来说很合适。谢谢!这是我的代码:
import UIKit
import MapKit
import CoreData
class MapViewController: UIViewController, MKMapViewDelegate {
//Variables
var locationManager = CLLocationManager()
var currentPins = [Pin]()
var gestureBegin: Bool = false
var sharedContext: NSManagedObjectContext {
return CoreDataStack.sharedInstance().managedObjectContext
}
//Fetch All Pins
func fetchAllPins() -> [Pin] {
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Pin")
do {
return try sharedContext.fetch(fetchRequest) as! [Pin]
} catch {
print("Error In Fetch!")
return [Pin]()
}
}
//Outlets
@IBOutlet weak var mapView: MKMapView!
//Core Dat
override func viewDidLoad() {
super.viewDidLoad()
let longPressRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(MapViewController.longPressGesture(longPress:)))
longPressRecognizer.minimumPressDuration = 1.5
mapView.addGestureRecognizer(longPressRecognizer)
self.mapView.delegate = self
addSavedPinsToMap()
}
//Add Saved Pin To Map
func addSavedPinsToMap() {
currentPins = fetchAllPins()
print("Pins Count in Core Data Is \(currentPins.count)")
for currentPin in currentPins {
let annotation = MKPointAnnotation()
annotation.coordinate = currentPin.coordinate
mapView.addAnnotation(annotation)
}
}
//Long Press Gesture Recognizer
func longPressGesture(longPress: UIGestureRecognizer) {
//Take Point
let touchPoint = longPress.location(in: self.mapView)
//Convert Point To Coordinate From View
let touchMapCoordinate = mapView.convert(touchPoint, toCoordinateFrom: mapView)
//Init Annotation
let annotation = MKPointAnnotation()
annotation.coordinate = touchMapCoordinate
//Init New Pin
let newPin = Pin(latitude: annotation.coordinate.latitude, longitude: annotation.coordinate.longitude, context: sharedContext)
//Save To Core Data
CoreDataStack.sharedInstance().saveContext()
//Adding New Pin To Pins Array
currentPins.append(newPin)
//Add New Pin To Map
mapView.addAnnotation(annotation)
}
} // End Class
这是我的核心数据文件:
import Foundation
import CoreData
import MapKit
//Pin Class
public class Pin: NSManagedObject {
var coordinate: CLLocationCoordinate2D {
return CLLocationCoordinate2D(latitude: latitude, longitude: longitutde)
}
convenience init(latitude: Double, longitude: Double, context: NSManagedObjectContext) {
if let ent = NSEntityDescription.entity(forEntityName: "Pin", in: context) {
self.init(entity: ent, insertInto: context)
self.latitude = latitude
self.longitutde = longitude
} else {
fatalError("Unable To Find Entity Name!")
}
}
}
另一个核心数据文件:
import Foundation
import CoreData
extension Pin {
@nonobjc public class func fetchRequest() -> NSFetchRequest<Pin> {
return NSFetchRequest<Pin>(entityName: "Pin")
}
@NSManaged public var latitude: Double
@NSManaged public var longitutde: Double
}
答案 0 :(得分:0)
想出我在我的VC中没有正确设置我的水龙头手势。一旦我确定插座连接到VC,一切正常。