Is it possible to serialize a SwiftUI view (i.e. not the ViewModel/state info, but the actual view itself)?

Viewed 371

Does Apple provide any way to serialize/deserialize a SwiftUI view for persistence reasons? To be clear, I mean the views themselves, not the data used to build them. I know Apple doesn't give us access to the view tree/hierarchy itself, which makes sense because they aren't 'objects' in a hierarchy, but there are view types, each with state, so I'm wondering if that can somehow be captured/persisted then recreated.

I'm asking because we're trying to mirror/mimic a similar concept in Windows WPF applications where you can serialize/deserialize entire UI elements into what's known as XAML, or Extensible Application Markup Language which is an XML format. You can store that data in say, a database, then reload it at runtime, rehydrating an entire UI, including bindings to data. While we don't need anything that elaborate--we just need loading static views--I'm not finding anything on this topic.

Now I know I could write my own 'builder' classes that look for types that I define from known 'model' types, then dynamically build up those views accordingly, but that would require writing an entire engine just for that limited purpose. So... is there any such thing already out there, or is this just not possible by design?

1 Answers

Yes! You can serialize a SwiftUI view. Just conform to the Codable protocol and you are good to go. Here is a small example:

import UIKit
import PlaygroundSupport
import SwiftUI

struct ContentView: View, Codable {
    var body: some View {
        VStack {
            Text("Hello World")
        }
    }
}

PlaygroundPage.current.setLiveView(ContentView())


let data = try? JSONEncoder().encode(ContentView())
print(data)

let contentView = try? JSONDecoder().decode(ContentView.self, from: data!)
print(contentView)

Related