将CLLocationCoordinate2D转换为可以存储的String

时间:2015-06-12 06:37:18

标签: ios swift location cllocation nscoding

我试图在一个ViewController中保存用户的坐标,以便它可以用来创建可以在另一个ViewController中显示的注释。

在使用代码

存储坐标I&m; m的视图控制器中
NSUserDefaults.standardUserDefaults().setObject( Location, forKey: "Location")

在显示注释的地图视图控制器中,我试图使用代码获取坐标

let Location = NSUserDefaults.standardUserDefaults().stringForKey("Location")
var Annotation = MKPointAnnotation()
Annotation.coordinate = Location    

它告诉我String?类型的值为CLLocationCoordinate2D类型的值。

那么如何将CLLocationCoordinate2D坐标转换为String类型的值?

3 个答案:

答案 0 :(得分:7)

这样您就可以将地点存储到NSUserDefaults

//First Convert it to NSNumber.
let lat : NSNumber = NSNumber(double: Location.latitude)
let lng : NSNumber = NSNumber(double: Location.longitude)

//Store it into Dictionary
let locationDict = ["lat": lat, "lng": lng]

//Store that Dictionary into NSUserDefaults
NSUserDefaults.standardUserDefaults().setObject(locationDict, forKey: "Location")

之后你可以这样访问它:

//Access that stored Values
let userLoc = NSUserDefaults.standardUserDefaults().objectForKey("Location") as! [String : NSNumber]

//Get user location from that Dictionary
let userLat = userLoc["lat"]
let userLng = userLoc["lng"]

var Annotation = MKPointAnnotation()

Annotation.coordinate.latitude = userLat as! CLLocationDegrees  //Convert NSNumber to CLLocationDegrees
Annotation.coordinate.longitude = userLng as! CLLocationDegrees //Convert NSNumber to CLLocationDegrees

<强>更新

HERE是您的示例项目。

答案 1 :(得分:2)

extension CLLocationCoordinate2D:Printable
{
    init(coords : String)
    {
        var fullNameArr = split(coords) {$0 == ";"}
        self.latitude = NSNumberFormatter().numberFromString(fullNameArr[0])!.doubleValue
        self.longitude = (fullNameArr.count > 1) ? NSNumberFormatter().numberFromString(fullNameArr[1])!.doubleValue : 0
    }

    public var description : String
    {
        return "\(self.latitude);\(self.longitude)"
    }
}

然后在示例代码中使用:


    var coord = CLLocationCoordinate2D(latitude: 3.2, longitude: 6.4)
    NSUserDefaults.standardUserDefaults().setObject(coord.description, forKey: "Location")
    var readedCoords = CLLocationCoordinate2D(coords: NSUserDefaults.standardUserDefaults().stringForKey("Location")!)

答案 2 :(得分:0)

您可以存储纬度或经度(或两者都存储在字典或元组中)。将它们包装在String中的方法:

func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    var locValue:CLLocationCoordinate2D = manager.location!.coordinate        
    var lat : String = locValue.latitude.description
    var lng : String = locValue.longitude.description
    //do whatever you want with lat and lng
}