I just copy all the code from this course and try to run it, but it always print 'Unable to load saved data.' at the begining.
For debug, I added some prints like this:
func loadData() {
let filename = getDocumentsDirectory().appendingPathComponent("SavedPlaces")
do {
let data = try Data(contentsOf: filename)
print("get data")
locations = try JSONDecoder().decode([CodableMKPointAnnotation].self, from: data)
} catch {
print("Unable to load saved data.")
}
}
func saveData() {
do {
let filename = getDocumentsDirectory().appendingPathComponent("SavedPlaces")
let data = try JSONEncoder().encode(self.locations)
try data.write(to: filename, options: [.atomicWrite, .completeFileProtection])
} catch {
print("Unable to save data.")
}
print("Saved data")
}
After that, it can print 'Saved data' and 'get data', but it always print "Unable to load saved data."
For the CodableMKPointAnnotation:
class CodableMKPointAnnotation: MKPointAnnotation, Codable {
enum CodingKeys: CodingKey {
case title, subtitle, latitude, longitude
}
override init() {
super.init()
}
public required init(from decoder: Decoder) throws {
super.init()
let container = try decoder.container(keyedBy: CodingKeys.self)
title = try container.decode(String.self, forKey: .title)
subtitle = try container.decode(String.self, forKey: .subtitle)
let latitude = try container.decode(CLLocationDegrees.self, forKey: .latitude)
let longitude = try container.decode(CLLocationDegrees.self, forKey: .longitude)
coordinate = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(title, forKey: .title)
try container.encode(subtitle, forKey: .subtitle)
try container.encode(coordinate.latitude, forKey: .latitude)
try container.encode(coordinate.longitude, forKey: .longitude)
}
}
So, how can I fix the problem?