Search code examples
iosswiftnsuserdefaultscllocationcoordinate2d

NSUserDefaults and using setobject method to store CLLocationCoordinate2D error in Swift


I found the answer to this question here: Store CLLocationCoordinate2D to NSUserDefaults. And the code is written in Objective C. I understand, for the most part, what is happening with the code in that link. However, it is difficult for me to translate the syntax over to Swift. And I think it would be helpful for others to have this translation as well.

Just to reiterate the error, it is: Cannot invoke 'setObject' with an argument list of type (CLLocationCoordinate2D, forKey: String!). And here is the syntax that is causing this problem:

let mapAnnotations = NSUserDefaults.standardUserDefaults()
let newCoordinate = self.mapView.convertPoint(touchPoint, toCoordinateFromView: self.mapView)
var title: String! = ""
self.mapAnnotations.setObject(newCoordinate, forKey: title) //the error is here
self.mapAnnotations.synchronize()

Solution

  • Just change your code to the following

    let mapAnnotations = NSUserDefaults.standardUserDefaults()
    let newCoordinate = self.mapView.convertPoint(touchPoint, toCoordinateFromView: self.mapView)
    let lat = NSNumber(double: newCoordinate.latitude)
    let lon = NSNumber(double: newCoordinate.longitude)
    let userLocation: NSDictionary = ["lat": lat, "long": lon]
    self.mapAnnotations.setObject(userLocation, forKey: "userLocation") //the error is here
    self.mapAnnotations.synchronize()
    

    What I've done is:

    • Create two NSNumber objects with the Doubles and collected them in an NSDictionary (and not a Swift Dictionary).
    • Passed this NSDictionary to be saved by your NSUserDefaults, which should accept it now, just like the Objective-C code.