在 SwiftUI 中使用协调器模式时未调用 CNContactViewControllerDelegate

CNContactViewControllerDelegate not called when using the Coordinator pattern in SwiftUI

我已经在这个问题上研究了好几天了,似乎 SwiftUI 的相对“新”似乎并没有帮助我解决这个问题。

我的直觉是我在某种程度上使用了 CNContactViewControllerDelegate 错误,但 Apple 的文档以及关于 SO 的其他问题使它看起来应该有效。也许,这也是由 .sheet 的处理引起的,但我也无法隔离问题。不将 NewContactView 包装在 NavigationView 内也没有任何区别,并删除了默认导航栏(如预期的那样)。

我正在展示 CNContactViewControllerinit(forNewContact:) 以使应用程序的用户能够添加新联系人。坚持并且一切正常,但是,none 委托函数似乎被调用。

既没有使用 iOS 13 中引入的“滑动以关闭”手势关闭模态调用委托函数,也没有使用 CNContactViewController 提供的导航按钮。

import Foundation
import SwiftUI
import ContactsUI

struct NewContactView: UIViewControllerRepresentable {
    class Coordinator: NSObject, CNContactViewControllerDelegate, UINavigationControllerDelegate {

        func contactViewController(_ viewController: CNContactViewController, didCompleteWith contact: CNContact?) {
            if let c = contact {
                self.parent.contact = c
            }
            viewController.dismiss(animated: true)
        }
        
        func contactViewController(_ viewController: CNContactViewController, shouldPerformDefaultActionFor property: CNContactProperty) -> Bool {
            return true
        }

        var parent: NewContactView

        init(_ parent: NewContactView) {
            self.parent = parent
        }
    }

    @Binding var contact: CNContact

    init(contact: Binding<CNContact>) {
        self._contact = contact
    }

    typealias UIViewControllerType = CNContactViewController

    func makeCoordinator() -> Coordinator {
        return Coordinator(self)
    }

    func makeUIViewController(context: UIViewControllerRepresentableContext<NewContactView>) -> NewContactView.UIViewControllerType {
        let vc = CNContactViewController(forNewContact: CNContact())
        vc.delegate = makeCoordinator()
        return vc
    }

    func updateUIViewController(_ uiViewController: NewContactView.UIViewControllerType, context: UIViewControllerRepresentableContext<NewContactView>) {
    }
}

显示控制器的视图代码如下所示:

.sheet(isPresented: self.$viewModel.showNewContact, onDismiss: { self.viewModel.fetchContacts() }) {
        NavigationView() {
                NewContactView(contact: self.$viewModel.newContact)
        }
}

多谢指点!可悲的是,Rubberducking 没有帮助...

SwiftUI 自己创建协调器,并提供给上下文中的可表示,所以只需使用

    func makeUIViewController(context: UIViewControllerRepresentableContext<NewContactView>) -> NewContactView.UIViewControllerType {
        let vc = CNContactViewController(forNewContact: CNContact())
        vc.delegate = context.coordinator      // << here !!
        return vc
    }