0

Having difficulty trying to use an @Published property in my Mac app within a class that needs to be Codable.

This class is initialised using an AVMutableComposition.

I followed this tutorial here and came up with the following, but not sure what to do to encode/decode an AVPlayerItem as the following code still gives me two errors:

Instance method 'decode(_:forKey:)' requires that 'AVPlayerItem' conform to 'Decodable'

and

Instance method 'encode(_:forKey:)' requires that 'AVPlayerItem' conform to 'Encodable'

class ProjectState2: ObservableObject, Codable {
    enum CodingKeys: CodingKey{
        case video
    }

    @Published var video: AVPlayerItem
    
    public required init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        video = try container.decode(AVPlayerItem.self, forKey: .video)
    }
    
    public func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)
        try container.encode(video, forKey: .video)
    }

}
user1542125
  • 593
  • 6
  • 16
  • 2
    How do you initialize this item? using a URL? or maybe an AVAsset? which is init from a URL as well or Data? You should used the underlying representation of the item and cache/persist it and not the abstraction that allow interaction with AVFoundation – CloudBalancing Nov 01 '22 at 04:51
  • I'm initialising from an AVMutableComposition – user1542125 Nov 01 '22 at 05:08
  • 1
    Agree with the first comment -- it's unlikely that storing the item in something `Codable` is going to be a good strategy. Can you explain what your end goal is (eg *why* you want to use Codable here)? – jnpdx Nov 01 '22 at 05:18
  • The AVMutableComposition (AVPlayerItem) can be changed by many parts of my application. So I have a single source of this. The AVMutableComposition is created from a changing list of AVURLAssets. I was hoping to just be able to @Publish a new AVPlayerItem so that my AVPlayer always has the latest composition. The only other pathway I was going to head down was to use Notification Center to announce changes to the list of AVURLAsset and regenerate the AVMutableComposition (AVPlayerItem), and somehow tell my AVPlayer to reload. This is all in SwiftUI BTW. Hope this makes sense. – user1542125 Nov 01 '22 at 05:28
  • 2
    You can use `@Published` without it being Codable. Why is the `Codable `part necessary? – jnpdx Nov 01 '22 at 05:31
  • The app is a document-based app. All of the URLs in the AVURLAssets list are in there as json (which is why the parent class is Codable). I was hoping to add the @Published variable to this class to make access to the data simpler. – user1542125 Nov 01 '22 at 05:40
  • I get the feeling I'm misusing SwiftUI and creating too many data sources. – user1542125 Nov 01 '22 at 05:41

0 Answers0