swift - 当我离开应用程序时,如何保存我的 MapView 注释?
问题描述
func addPin(_ sender: UILongPressGestureRecognizer) {
let location = sender.location(in: self.mapView)
let locCoord = self.mapView.convert(location, toCoordinateFrom: self.mapView)
let annotation = MKPointAnnotation()
annotation.coordinate = locCoord
annotation.title = titleTextField.text
self.mapView.addAnnotation(annotation)
print("This will become the annotation title: \(titleTextField.text).")
print(annotation.coordinate.latitude, annotation.coordinate.longitude)
}
我是 swift 新手,想知道如何在离开应用程序后保存我的注释。另外,如果用户不拿起手指,如何阻止形成多个注释?
解决方案
您可能需要做的是将MKPointAnnotation
s 存储为Data
within UserDefaults
。为此,您将从 mapView 的所有注释中创建一个字典数组:
func addPin(_ sender: UILongPressGestureRecognizer) {
let location = sender.location(in: self.mapView)
let locCoord = self.mapView.convert(location, toCoordinateFrom: self.mapView)
let annotation = MKPointAnnotation()
annotation.coordinate = locCoord
annotation.title = titleTextField.text
self.mapView.addAnnotation(annotation)
//Create a dictionary from the annotation
let newAnnotationDict = [
"lat": locCoord.latitude
"lng": locCoord.longitude
"title": annotation.title
]
//Pull the stored annotations data
var annotationsArray: [[String:Any]]!
var annotationsData = UserDefaults.standard.data(forKey: "StoredAnnotations")
//If the data is nil, then set the new annotation as the only element in the array
if annotationsData == nil {
annotationsArray = [newAnnotationDict]
} else {
//If it isn't nil, then convert the data into an array of dicts
do {
//Convert this data into an array of dicts
annotationsArray = try JSONSerialization.jsonObject(with: annotationsData, options: []) as! [[String:Any]]
annotationsArray.append(newAnnotationDict)
} catch {
print(error.localizedDescription)
}
}
do {
//Use JSONSerialization to convert the annotationsArray into Data
let jsonData = try JSONSerialization.data(withJSONObject: annotationsArray, options: .prettyPrinted)
//Store this data in UserDefaults
UserDefaults.standard.set(jsonData, forKey: "StoredAnnotations")
} catch {
print(error.localizedDescription)
}
print("This will become the annotation title: \(titleTextField.text).")
print(annotation.coordinate.latitude, annotation.coordinate.longitude)
}
然后,当视图控制器再次打开时,您需要从中提取Data
它并将其解析为对象UserDefaults
数组。MKPointAnnotation
class MapViewController: UIViewController {
//Whenever the view loads, check if there were any annotations stored last time
override func viewDidLoad() {
super.viewDidLoad()
//Check if the data for "StoredAnnotations" exists
if UserDefaults.standard.data(forKey: "StoredAnnotations") != nil {
var storedAnnotationObjects = [MKPointAnnotation]()
do {
//Get the data from UserDefaults
let storedAnnotationsData = UserDefaults.standard.data(forKey: "StoredAnnotations")!
//Convert this data into an array of dictionaries
let storedAnnotationsArray = try JSONSerialization.jsonObject(with: storedAnnotationsData, options: []) as! [[String:Any]]
for dict in storedAnnotationsArray {
//Initialize a new annotation and set the annotation's properties
let newAnnotation = MKPointAnnotation()
newAnnotation.coordinate = CLLocationCoordinate2D(latitude: dict["lat"] as! CGFloat, longitude: dict["lng"] as! CGFloat)
newAnnotation.title = dict["title"] as! String
newAnnotationObjects.append(newAnnotation)
}
//Add the annotation to the mapView
self.mapView.annotations = storedAnnotationObjects
} catch {
print(error.localizedDescription)
}
}
}
...
}
如果要删除注释,您需要类似地将存储的数据转换为字典数组并删除适当的对象并更新数据。
推荐阅读
- android - 从sqlite数据库中删除后recyclerview没有更新
- r - 如何获得k个最小的元素?
- wpf - Josh Smith 关于 WPF 的文章:https://msdn.microsoft.com/en-us/magazine/dd419663.aspx
- react-native - 从数组 react-native 生成时,多个开关同时启用
- android-source - 谷歌为什么要发明特权权限白名单功能?
- python - 将 SNS 主题中的 instanceid 解析为 Lambda 触发器
- css - 如何防止元素在其动画被删除时回弹?
- python - 如何按频率对 NumPy 数组进行排序?
- scheme - 将字符串原始函数导入 MIT 方案
- javascript - 为什么“重复组件”中的回调函数总是指向最后一个以角度重复的组件?