Saving map pins to array, Swift

不问归期 提交于 2019-12-06 08:14:32

If you want to persist data between application launches, and you are not storing much data, the easy way is to use NSUserDefaults. You can do this by saying something like:

func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    let location = locations.last
    let center = CLLocationCoordinate2D(latitude: location!.coordinate.latitude, longitude: location!.coordinate.longitude)
    let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.004, longitudeDelta: 0.004))
    self.placesMap?.setRegion(region, animated: true)
    self.locationManager.stopUpdatingLocation()



     let locationDictionary:[String:Double] = ["latitude":center.latitude,"longitude":center.longitude]
     var locationArray = [[String:Double]]()
     if NSUserDefaults.standardUserDefaults().objectForKey("locationArray") != nil {
        locationArray = NSUserDefaults.standardUserDefaults().objectForKey("locationArray") as! [[String:Double]]

    }

    locationArray.append(locationDictionary)

    NSUserDefaults.standardUserDefaults().setObject(locationArray, forKey: "locationArray")
    NSUserDefaults.standardUserDefaults().synchronize()
    }

You will then need to read out those locations when the app relaunches. You can do that in viewDidLoad. For example:

override func viewDidLoad(){
    super.viewDidLoad()
    if NSUserDefaults.standardUserDefaults().objectForKey("locationArray") != nil {
    for dictionary in NSUserDefaults.standardUserDefaults().objectForKey("locationArray") as! [[String:Double]]{
        let center = CLLocationCoordinate2D(latitude: dictionary["latitude"]!, longitude: dictionary["longitude"]!)
        let annotation = MKPointAnnotation()
        annotation.coordinate = center
        self.placesMap.addAnnotation(annotation)
    }
  }
}

If you want to remove all of the stored locations you can say something like:

    func removeStoredLocations(){
     NSUserDefaults.standardUserDefaults().removeObjectForKey("locationArray")
     NSUserDefaults.standardUserDefaults().synchronize()
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!