我正在 SwiftUI 应用程序中使用 researchkit 进行一项研究。每次我调用研究工具包任务时,应用程序都会崩溃并显示以下错误:
*** 由于未捕获的异常“NSInvalidArgumentException”而终止应用程序,原因:“-[SwiftUI.AppDelegate 窗口]:无法识别的选择器发送到实例 0x600000c511c0” 以 NSException 类型的未捕获异常终止
我目前有一些时间调试。代码如下:
struct activityView: UIViewControllerRepresentable {
var activity: activity
var onCompleted: (Bool) -> Void
func makeUIViewController(context: Context) -> ORKTaskViewController {
let result: ORKTaskViewController
switch activity {
case .survey:
result = ORKTaskViewController(task: StudyTasks.surveyTask,taskRun: NSUUID() as UUID)
case .microphone:
result = ORKTaskViewController(task: StudyTasks.microphonetask,taskRun: NSUUID() as UUID)
do {
let defaultFileManager = FileManager.default
// Identify the documents directory.
let documentsDirectory = try defaultFileManager.url(for: .documentDirectory,in: .userDomainmask,appropriateFor: nil,create: false)
// Create a directory based on the `taskRunUUID` to store output from the task.
let outputDirectory = documentsDirectory.appendingPathComponent(result.taskRunUUID.uuidString)
try defaultFileManager.createDirectory(at: outputDirectory,withIntermediateDirectories: true,attributes: nil)
result.outputDirectory = outputDirectory
} catch let error as NSError {
fatalError("The output directory for the task with UUID: \(result.taskRunUUID.uuidString) could not be created. Error: \(error.localizedDescription)")
}
case .tapping:
result = ORKTaskViewController(task: StudyTasks.tappingTask,taskRun: NSUUID() as UUID)
case .trailmaking:
result = ORKTaskViewController(task: StudyTasks.trailmakingTask,taskRun: NSUUID() as UUID)
}
result.view.window?.tintColor = UIColor(named: "accentColor")
return result
}
func updateUIViewController(_ uiViewController: ORKTaskViewController,context: Context) {
uiViewController.delegate = context.coordinator
}
func makeCoordinator() -> Coordinator {
Coordinator(onCompleted: onCompleted)
}
class Coordinator: NSObject,ORKTaskViewControllerDelegate {
var onCompleted: (Bool) -> Void
init(onCompleted: @escaping (Bool) -> Void) {
self.onCompleted = onCompleted
}
public func taskViewController(_ taskViewController: ORKTaskViewController,didFinishWith reason: ORKTaskViewControllerFinishReason,error: Error?) {
self.onCompleted(reason == .completed)
}
func taskViewController(_ taskViewController: ORKTaskViewController,viewControllerFor step: ORKStep) -> ORKStepViewController? {
return nil
}
}
}