Group Group Group Group Group Group Group Group Group

Chapter 4--Hosting ViewControllers In SwiftUI

I am using the code in the book to host a ViewController in a SwiftUI project. I use instead of “ViewController”, “DocumentSaveViewController” and my StoryBoard ID is “DocumentSave”. Compiles okay but when I hit the Text(“Save File”) I get a Thread 1: signal SIGABRT and in the DocumentSaveViewController’s ViewControllerRepresentation struct :

struct ViewControllerRepresentation: UIViewControllerRepresentable {

func makeUIViewController(
context: UIViewControllerRepresentableContext
) -> DocumentSaveViewController {
UIStoryboard(name: “Main”, bundle: nil)
.instantiateViewController(withIdentifier: “DocumentSave”)
as! DocumentSaveViewController // this is the line where the program stops
}

func updateUIViewController(_ uiViewController: DocumentSaveViewController,
context: UIViewControllerRepresentableContext
) {
}
}

This struct is outside the DocumentSaveViewController class. Is this because I don’t use “ViewController”?

hi Garrett!

The context argument should be

context: UIViewControllerRepresentableContext<ViewControllerRepresentation>)

The struct in the angle brackets is whatever you named your UIViewControllerRepresentable struct. In this case, you kept it as ViewControllerRepresentation.

Strange, my code won’t compile without it.

Since it crashes in this line:

UIStoryboard(name: “Main”, bundle: nil)
    .instantiateViewController(withIdentifier: “DocumentSave”)
    as! DocumentSaveViewController 

I would say that probably it’s because it can’t find a view controller with the DocumentSave identifier, or it cannot be cast to DocumentSaveViewController - I would double check both cases. Have you updated the “custom class” of the view controller in the storyboard?