I am trying to build a SwiftUI tvOS app. As you can see here, I am trying to create a SwiftUI View using a UIViewControllerRepresentable, specifically for the DDDevicePickerViewController.

However, I noticed that there is no DDDevicePickerViewControllerDelegate while I was trying to implement it, which is needed according to Paul Hudson's tutorial. How can I use the DevicePickerView in SwiftUI?

I tried to use this code to create it, so when I use it, I just get a black screen with no errors in the logs:

import Foundation
import SwiftUI
import DeviceDiscoveryUI

public struct DDevicePickerView: UIViewControllerRepresentable {
    let viewController: DDDevicePickerViewController

    public init() {
        // Create the view controller for the device picker.
        let devicePicker = DDDevicePickerViewController(browseDescriptor: .applicationService(name: "TicTacToe"),
                                                              parameters: applicationServiceParameters())
        self.viewController = devicePicker!
    }

    public func makeUIViewController(context: Context) -> DDDevicePickerViewController {
        let gkVC = viewController
        return gkVC
    }

    public func updateUIViewController(_ uiViewController: DDDevicePickerViewController, context: Context) {
        return
    }
}
1

There are 1 best solutions below

3
On

SwiftUI already has a wrapper DevicePicker

But if you want to wrap it yourself, start with something like this and then you just have to figure out how to get the async endpoint result. It is quite unusual to have view controllers be async like this.

import Foundation
import SwiftUI
import DeviceDiscoveryUI

public struct DevicePicker: UIViewControllerRepresentable {
    @Binding var isPresented: Bool

    public func makeUIViewController(context: Context) -> UIViewController {
        UIViewController()
    }

    public func updateUIViewController(_ uiViewController: UIViewController, context: Context) {
        if isPresented {
             if uiViewController.presentedViewController != nil {
                 return
             }
             
             let = picker DDDevicePickerViewController(browseDescriptor: .applicationService(name: "TicTacToe"), parameters: applicationServiceParameters())
              uiViewController.present(picker, animated: !context.transaction.disablesAnimations)
        }
        else {
            uiViewController.presentedViewController?.dismiss()
        }
    }
}