Storing CLLocation and keeping annotation

天涯浪子 提交于 2019-12-13 05:03:44

问题


My app currently has three tabs, a tab for pinning a location, and a detailView of the pinned location on the second tab. I am trying to save the location of the pin into NSUserdefaults. I would then like that location to stay pinned upon reloading the app, and therefore the detail view would still display the detail view of the pinned location. Here is what I have so far,

func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
    // Find location of user
    var userLocation:CLLocation = locations[0] as! CLLocation
    var latitude = userLocation.coordinate.latitude
    var longitude = userLocation.coordinate.longitude
    var latDelta:CLLocationDegrees = 0.01
    var longDelta: CLLocationDegrees = 0.01
    var span: MKCoordinateSpan = MKCoordinateSpanMake(latDelta, longDelta)
    var location:MKUserLocation = currentLocation;
    var region: MKCoordinateRegion = MKCoordinateRegionMake(location.coordinate, span)
    var coordinate:CLLocationCoordinate2D = CLLocationCoordinate2DMake(latitude, longitude);
    carInitialLocation = userLocation;
    let locationData = NSKeyedArchiver.archivedDataWithRootObject(carInitialLocation);
    NSUserDefaults.standardUserDefaults().setObject(locationData, forKey: "locationData");
    carInitialCoordinate = coordinate;

    self.map.setRegion(region, animated: true);
}


override func viewDidLoad() {

    super.viewDidLoad()
    if let loadedData = NSUserDefaults.standardUserDefaults().dataForKey("locationData") {
        if let loadedLocation = NSKeyedUnarchiver.unarchiveObjectWithData(loadedData) as? CLLocation {
            println(loadedLocation.coordinate.latitude);
            println(loadedLocation.coordinate.longitude);
            var annotation = MKPointAnnotation()
            annotation.coordinate = loadedLocation.coordinate
            annotation.title = title
            self.map.addAnnotation(annotation)

        }
    }

    map.addAnnotations(artworks)
    map.delegate = self;
    manager.delegate = self;
    manager.desiredAccuracy = kCLLocationAccuracyBest;
    manager.requestWhenInUseAuthorization();
    manager.startUpdatingLocation();
    self.map.showsUserLocation = true;
    currentLocation = map.userLocation;
}

I then want the pinLocation button to be deactivated once the user has pinned a location once. I try to do this as so:

@IBAction func pinLocationButton(sender: AnyObject) {
    // add location to the array, so it can be retrieved and put it into temporary storage
    //places.append(["name":title,"lat":"\(newCoordinate.latitude)","lon":"\(newCoordinate.longitude)"])
    if let loadedData = NSUserDefaults.standardUserDefaults().dataForKey("locationData") {
        if let loadedLocation = NSKeyedUnarchiver.unarchiveObjectWithData(loadedData) as? CLLocation {
            println(loadedLocation.coordinate.latitude);
            println(loadedLocation.coordinate.longitude);
            pinLocationButton.enabled = false;

        }
    }


    var location = carInitialLocation
    var coordinate = carInitialCoordinate

    CLGeocoder().reverseGeocodeLocation(manager.location, completionHandler: { (placemarks, error) -> Void in
        var title = ""
        if (error == nil) {
            if let p = CLPlacemark(placemark: placemarks?[0] as! CLPlacemark) {

                var subThoroughfare:String = ""
                var thoroughfare:String = ""

                if p.subThoroughfare != nil {

                    subThoroughfare = p.subThoroughfare
                }
                if p.thoroughfare != nil {

                    thoroughfare = p.thoroughfare

                }
                completeAddress = self.displayLocationInfo(p);
                title = "\(subThoroughfare) \(thoroughfare)"
            }
        }
                    // annotation, i.e pins

    var annotation = MKPointAnnotation()
    annotation.coordinate = coordinate
    annotation.title = title
    self.map.addAnnotation(annotation)
       // NSUserDefaults.standardUserDefaults().setObject(places, forKey: "places")
    })
}

Then, in my detailVC I attempt to reverse geocode the pinned location, but it is defaulting to the current location.. which I don't understand why Here's the code:

super.viewDidLoad()

    addressLabel.font = UIFont(name: addressLabel.font.fontName, size: 18)
    smallMapView.delegate = self;
    locationManager.delegate = self;
    smallMapView.mapType = MKMapType.Hybrid;
    locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    locationManager.requestWhenInUseAuthorization();
    locationManager.startUpdatingLocation();
    smallMapView.zoomEnabled = true;
    smallMapView.rotateEnabled = true;

    if let loadedData = NSUserDefaults.standardUserDefaults().dataForKey("locationData") {
        if let loadedLocation = NSKeyedUnarchiver.unarchiveObjectWithData(loadedData) as? CLLocation {
            println(loadedLocation.coordinate.latitude);
            println(loadedLocation.coordinate.longitude);

            CLGeocoder().reverseGeocodeLocation(loadedLocation, completionHandler: { (placemarks, error) -> Void in
                var title = "";
                var subtitle = "";
                var locality = "";
                if(error == nil) {
                    if let placemark = CLPlacemark(placemark: placemarks?[0] as! CLPlacemark) {
                        var subThoroughfare:String = "";
                        var thoroughfare:String = "";
                        var locality:String = "";
                        var postalCode:String = "";
                        var administrativeArea:String = "";
                        var country:String = "";

                        if (placemark.subThoroughfare != nil) {
                            subThoroughfare = placemark.subThoroughfare;
                        }
                        if(placemark.thoroughfare != nil) {
                            thoroughfare = placemark.thoroughfare;
                        }
                        if(placemark.locality != nil) {
                            locality = placemark.locality;
                        }
                        if(placemark.postalCode != nil) {
                            postalCode = placemark.postalCode;
                        }
                        if(placemark.administrativeArea != nil) {
                            administrativeArea = placemark.administrativeArea;
                        }
                        if(placemark.country != nil) {
                            country = placemark.country;
                        }
                        println("viewcontroller placmark data:");
                        println(locality);
                        println(postalCode);
                        println(administrativeArea);
                        println(country);

                        title = " \(subThoroughfare) \(thoroughfare) \n \(locality), \(administrativeArea) \n \(postalCode) \(country)";
                        subtitle = " \(subThoroughfare) \(thoroughfare)";
                        println(title);
                        self.addressLabel.text = title;
                    }
                }
                var latitude = loadedLocation.coordinate.latitude;
                var longitude = loadedLocation.coordinate.longitude;
                var latDelta:CLLocationDegrees = 0.001;
                var longDelta:CLLocationDegrees = 0.001;

                var span: MKCoordinateSpan = MKCoordinateSpanMake(latDelta, longDelta);
                var overallLoc = CLLocationCoordinate2DMake(latitude, longitude);
                var region:MKCoordinateRegion = MKCoordinateRegionMake(overallLoc, span);
                var annotation = MKPointAnnotation();
                annotation.coordinate = loadedLocation.coordinate;
                annotation.title = subtitle;
                self.smallMapView.addAnnotation(annotation);
                self.smallMapView.setRegion(region, animated: true)

            })

        }
    }


}

回答1:


in the pinLocationButton function, you use the manager.location which is wrong, you should use

CLGeocoder().reverseGeocodeLocation(location, completionHandler: { (placemarks, error) -> Void in
    var title = ""
    if (error == nil) {
    // ....


来源:https://stackoverflow.com/questions/31465870/storing-cllocation-and-keeping-annotation

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!