local-storageuserdefaultscustom-object

How can I store a custom object in UserDefaults?


I have a struct called Note with some basic properties like id, title, body. But i also have a property location of type CLLocationCoordinate2D. I want to provide local storage with UserDefaults. Because CLLocationCoordinate2D does not conform to the Codable Protocol I used the automatic help from Xcode that created an extension with two protocol stubs. It looks like that:

extension CLLocationCoordinate2D: Codable {
    public init(from decoder: Decoder) throws {
        <#code#>
    }
    
    public func encode(to encoder: Encoder) throws {
        <#code#>
    }
}

struct Note: Codable {
    let id: UUID
    let title: String
    let body: String
    var location: CLLocationCoordinate2D
}

and this is the point where i need help. Because i don't know how to fill the gaps marked with <#code#>. Maybe someone could give a hint. Any help is highly appreciated.


Solution

  • After some research I found the solution here developer.apple.com/

    extension CLLocationCoordinate2D: Codable {
    
      enum CodingKeys: String, CodingKey {
        case latitude
        case longitude
      }
    
      public init(from decoder: Decoder) throws {
          self.init()
        
          let values = try decoder.container(keyedBy: CodingKeys.self)
          latitude = try values.decode(Double.self, forKey: .latitude)
          longitude = try values.decode(Double.self, forKey: .longitude)
       }
    
      public func encode(to encoder: Encoder) throws {
          var container = encoder.container(keyedBy: CodingKeys.self)
          try container.encode(latitude, forKey: .latitude)
          try container.encode(longitude, forKey: .longitude)
      }
    }