0

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()
Community
  • 1
  • 1
Jae
  • 321
  • 3
  • 12
  • Read the Apple documentation on `NSUserDefaults`, there are limitation on the things that it can save. – zaph Aug 28 '15 at 02:05
  • @zaph I understand that that is the case. However, it seems that this link: http://stackoverflow.com/questions/18910612/store-cllocationcoordinate2d-to-nsuserdefaults, provides a way in which you can store CLLocationCoordinate2D into NSUserDefaults. I just don't know the translation from Objective C to Swift. – Jae Aug 28 '15 at 02:09

1 Answers1

0

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.
pxlshpr
  • 986
  • 6
  • 15