我想將位置座標保存到核心數據中 - 存儲這些座標並找回它們的正確方法是什麼?將位置座標保存到核心數據 - Swift 3
目前我在做這一點,得到錯誤:
var newPlaceCoordinate = CLLocationCoordinate2D()
var newPlaceLatitude = CLLocationDegrees()
var newPlaceLongitude = CLLocationDegrees()
讓我的座標,從使用自動完成構件使用谷歌地圖API。
let newPlaceCoordinate = place.coordinate
self.newPlaceCoordinate = place.coordinate
let newPlaceLatitude = place.coordinate.latitude
print(newPlaceLatitude)
self.newPlaceLatitude = place.coordinate.latitude
let newPlaceLongitude = place.coordinate.longitude
print(newPlaceLongitude)
self.newPlaceLongitude = place.coordinate.longitude
然後保存我使用的座標:
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
let newPlace = NSEntityDescription.insertNewObject(forEntityName: "StoredPlace", into: context)
newPlace.setValue(newPlaceCoordinate, forKey: "coordinate")
newPlace.setValue(newPlaceLatitude, forKeyPath: "latitude")
newPlace.setValue(newPlaceLongitude, forKeyPath: "longitude")
我都設置爲字符串類型的屬性。 然後在我viewDidLoad中找回我:
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "StoredPlace")
request.returnsObjectsAsFaults = false
if let coordinate = result.value(forKey: "coordinate") as? String
{
let latitude = (coordinate as NSString).doubleValue
let longitude = (coordinate as NSString).doubleValue
let markers = GMSMarker()
markers.position = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
markers.icon = GMSMarker.markerImage(with: UIColor.yellow)
markers.tracksViewChanges = true
markers.map = vwGMap
}
所以這是行不通的,生產的「屬性的錯誤:屬性=‘協調’;期望的類型= NSString;給定類型= NSConcreteValue'。我有幾個問題。
如何正確保存座標數據? 我將它保存爲CLLocationDegrees或CLLocationCoordinate2D嗎? 如何將這些對象轉換爲NSString,或者我應該在屬性中使用不同的類型? (我試圖將其更改爲Double或Integer,但它也產生了錯誤)。我有多個位置座標,我想從核心數據中存儲和檢索。
謝謝你。我收到一個錯誤,說'Appdelegate沒有成員managedObjectContext' - 有什麼我應該添加? (我使用Swift 3和最新版本的Xcode,如果我從以前的版本中瞭解,他們已經改變了CoreData模板) –
如果你的部署目標是iOS 10,那麼應該使用appDelegate.persistentContainer.viewContext – Matt
所以我我已經試過了,但仍然有相同的錯誤。只要將屬性設置爲Double,它就會崩潰。我不知道爲什麼它不工作。在此期間,我通過將Long和Lat保存爲字符串來解決這個問題,並且它似乎可以很好地存儲到CoreData中。現在我正在努力研究如何將字符串轉換回CLLocationDegrees。你認爲這是一個適合存儲和檢索的方法嗎? –