Search code examples
swiftswiftuiresearchkit

How to close ResearchKit Modal view in SwiftUI?


I am using SwiftUI to program a research kit app for personal use and I was wondering how to interact with Modal View opened Research Kit survey task.

I am using this code at the moment to open the view:

struct SurveyView: UIViewControllerRepresentable {

typealias UIViewControllerType = ORKTaskViewController

func makeUIViewController(context: Context) -> ORKTaskViewController {

    let taskViewController = ORKTaskViewController(task: SurveyTask, taskRun: nil)
    taskViewController.view.tintColor = UIColor(red:0.64, green:0.15, blue:0.11, alpha:1.00)
    return taskViewController

}

func updateUIViewController(_ taskViewController: ORKTaskViewController, context: Context) {
    }

}

I am using a button to call it, however I can't make it close with the cancel or done button in research kit as I am in the dark as to where I should implement the didFinishWithReason reason: ORKTaskViewControllerFinishReason.

Any help would be very much appreciated.


Solution

  • I have managed to do it using Coordinators. If anyone is interested, here is the code.

    struct SurveyView: UIViewControllerRepresentable {
    func makeCoordinator() -> Coordinator {
        Coordinator()
    }
    
    
    typealias UIViewControllerType = ORKTaskViewController
    
    func makeUIViewController(context: Context) -> ORKTaskViewController {
    
        let taskViewController = ORKTaskViewController(task: SurveyTask, taskRun: nil)
        taskViewController.view.tintColor = UIColor(red:0.64, green:0.15, blue:0.11, alpha:1.00)
        taskViewController.delegate = context.coordinator
        return taskViewController
    
    }
    
    func updateUIViewController(_ taskViewController: ORKTaskViewController, context: Context) {
    
        }
    
    class Coordinator: NSObject, ORKTaskViewControllerDelegate {
        func taskViewController(_ taskViewController: ORKTaskViewController, didFinishWith reason: ORKTaskViewControllerFinishReason, error: Error?) {
            taskViewController.dismiss(animated: true, completion: nil)
        }
    }
    

    }