ios - 应用程序关闭后如何保存引脚注释(Swift)

标签 ios swift mapkit nsuserdefaults

目前,我的应用程序固定了一个位置,该位置是像这样的商店:

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;
    locationsDefaults.append(carInitialLocation);
    carInitialCoordinate = coordinate;

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

其中locationsDefaults 是我存储引脚位置的数组。

我想使用 NSUserdefaults,但我不太确定如何做到这一点,因为它不排除非 NS 数据。 Swift 中的指南/结构将不胜感激!

最佳答案

您可以将 NSData 保存到 NSUserDefaults。因此,您所需要做的就是使用 NSKeyedArchiver 将 CLLocation 对象转换为 NSData方法archivedDataWithRootObject如下:

// saving your CLLocation object
let locationData = NSKeyedArchiver.archivedDataWithRootObject(carInitialLocation)
NSUserDefaults.standardUserDefaults().setObject(locationData, forKey: "locationData")

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

关于ios - 应用程序关闭后如何保存引脚注释(Swift),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31464740/

相关文章:

ios - Firebase 通知 - 如何只向特定用户发送通知?

ios - 将 Json 数据数组添加到 Realm

swift - 如何在 Swift 中的 Parse 中进行嵌套查询

ios - 从 TabBar 注销

ios - 如何在 MKPointAnnotation 中设置标识符

ios - 无法将点击手势识别器添加到 SwiftUI MKMapView UIViewRepresentable

ios - UIView 过渡动画不执行

iphone - 有没有一种简单的方法可以查看可按下的链接?

swift - 将 NSPredicate/NSCompoundPredicate 与 Where 子句或可选返回值一起使用,CloudKit

swift - 将带有坐标的单个字符串转换为 CLLocationCoordinate2D 数组,并使用该数组在 mapView 中生成多边形