簡體   English   中英

將 CLLocationCoordinate2D 轉換為可存儲的 String

[英]Converting CLLocationCoordinate2D to a String that can be stored

我試圖在一個 ViewController 中保存用戶的坐標,以便它可以用於創建一個可以在另一個 ViewController 中顯示的注釋。

在存儲坐標的視圖控制器中,我使用了代碼

NSUserDefaults.standardUserDefaults().setObject( Location, forKey: "Location")

在顯示注釋的地圖視圖控制器中,我試圖使用代碼獲取坐標

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

它告訴我String?類型的值String? CLLocationCoordinate2D類型的值。

那么如何將CLLocationCoordinate2D坐標轉換為String類型的值?

這樣,您可以將Locations存儲到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

更新:

這里是您的示例項目。

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

然后在您的示例代碼中使用as:


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

您可以存儲緯度或經度(或同時存儲在字典或元組中)。 將它們包裝在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
}

使用 sprint 格式:

func Coord2String(location : CLLocationCoordinate2D) -> String {
    return  String(format : "latitude : %f, longitude : %f", location.latitude, location.longitude)
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM