ios - 存储 CLLocation 并保留注释

标签 ios swift mapkit

我的应用目前有三个选项卡,一个用于固定位置的选项卡,以及第二个选项卡上固定位置的详细 View 。我正在尝试将 pin 的位置保存到 NSUserdefaults 中。然后我希望该位置在重新加载应用程序时保持固定状态,因此详细 View 仍会显示固定位置的详细 View 。这是我目前所拥有的,

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;
}

然后我希望在用户固定位置一次后停用 pinLocation 按钮。我尝试这样做:

@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")
    })
}

然后,在我的 detailVC 中,我尝试对固定位置进行反向地理编码,但它默认为当前位置..我不明白为什么 这是代码:

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)

            })

        }
    }


}

最佳答案

在pinLocationButton函数中,你使用了错误的manager.location,你应该使用

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

关于ios - 存储 CLLocation 并保留注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31465870/

相关文章:

ios - map 不会更新到 iOS 7 中的新位置

iphone - 如何定义 MKAnnotationView 重叠的顺序?

ios - 无法从天气 api 获取 json。 iOS系统

ios - Xcode 7.3 Swift 的语法高亮和代码完成问题

iphone - 由于未捕获的异常 'CALayerInvalidGeometry' 而终止应用程序,原因 : 'CALayer bounds contains NaN: [0 nan; 280 524]'

swift - 为什么不能识别单元格的选择? swift

swift 泛型 : Constraining Argument Types

ios - 编译器错误设置存储属性的默认值 : trying to reference self

ios - RestKit - 到同一实体的关系映射创建无限循环

ios - 根据设备方向 iPhone 在 map View 上调整标注大小